main-seg.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
  2. """
  3. Train a YOLOv5 segment model on a segment dataset Models and datasets download automatically from the latest YOLOv5
  4. release.
  5. Usage - Single-GPU training:
  6. $ python segment/train.py --data coco128-seg.yaml --weights yolov5s-seg.pt --img 640 # from pretrained (recommended)
  7. $ python segment/train.py --data coco128-seg.yaml --weights '' --cfg yolov5s-seg.yaml --img 640 # from scratch
  8. Usage - Multi-GPU DDP training:
  9. $ python -m torch.distributed.run --nproc_per_node 4 --master_port 1 segment/train.py --data coco128-seg.yaml --weights yolov5s-seg.pt --img 640 --device 0,1,2,3
  10. Models: https://github.com/ultralytics/yolov5/tree/master/models
  11. Datasets: https://github.com/ultralytics/yolov5/tree/master/data
  12. Tutorial: https://docs.ultralytics.com/yolov5/tutorials/train_custom_data
  13. """
  14. import argparse
  15. import math
  16. import os
  17. import random
  18. import subprocess
  19. import sys
  20. import time
  21. from copy import deepcopy
  22. from datetime import datetime
  23. from pathlib import Path
  24. import numpy as np
  25. import torch
  26. import torch.distributed as dist
  27. import torch.nn as nn
  28. import yaml
  29. from torch.optim import lr_scheduler
  30. from tqdm import tqdm
  31. FILE = Path(__file__).resolve()
  32. ROOT = FILE.parents[0] # YOLOv5 root directory
  33. if str(ROOT) not in sys.path:
  34. sys.path.append(str(ROOT)) # add ROOT to PATH
  35. ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
  36. import segment.val as validate # for end-of-epoch mAP
  37. from models.experimental import attempt_load
  38. from models.yolo import SegmentationModel
  39. from utils.autoanchor import check_anchors
  40. from utils.autobatch import check_train_batch_size
  41. from utils.callbacks import Callbacks
  42. from utils.downloads import attempt_download, is_url
  43. from utils.general import (
  44. LOGGER,
  45. TQDM_BAR_FORMAT,
  46. check_amp,
  47. check_dataset,
  48. check_file,
  49. check_img_size,
  50. check_suffix,
  51. check_yaml,
  52. colorstr,
  53. get_latest_run,
  54. increment_path,
  55. init_seeds,
  56. intersect_dicts,
  57. labels_to_class_weights,
  58. labels_to_image_weights,
  59. one_cycle,
  60. print_args,
  61. print_mutation,
  62. strip_optimizer,
  63. yaml_save,
  64. )
  65. from utils.loggers import GenericLogger
  66. from utils.plots import plot_evolve, plot_labels
  67. from utils.segment.dataloaders import create_dataloader, create_dataloader_platform
  68. from utils.segment.loss import ComputeLoss
  69. from utils.segment.metrics import KEYS, fitness
  70. from utils.segment.plots import plot_images_and_masks, plot_results_with_masks
  71. from utils.torch_utils import (
  72. EarlyStopping,
  73. ModelEMA,
  74. de_parallel,
  75. select_device,
  76. smart_DDP,
  77. smart_optimizer,
  78. smart_resume,
  79. torch_distributed_zero_first,
  80. )
  81. from metrics.model2onnx import run as model2onnx
  82. import TrainSdk
  83. from metrics.image_test.seg_metrics import YoloType, YoloInstanceSegMetas, SegMetrics, ResizeMode
  84. LOCAL_RANK = int(os.getenv("LOCAL_RANK", -1)) # https://pytorch.org/docs/stable/elastic/run.html
  85. RANK = int(os.getenv("RANK", -1))
  86. WORLD_SIZE = int(os.getenv("WORLD_SIZE", 1))
  87. def train(hyp, opt, device, callbacks):
  88. """
  89. Trains the YOLOv5 model on a dataset, managing hyperparameters, model optimization, logging, and validation.
  90. `hyp` is path/to/hyp.yaml or hyp dictionary.
  91. """
  92. (
  93. save_dir,
  94. epochs,
  95. batch_size,
  96. weights,
  97. single_cls,
  98. evolve,
  99. data,
  100. cfg,
  101. resume,
  102. noval,
  103. nosave,
  104. workers,
  105. freeze,
  106. mask_ratio,
  107. is_train_on_platform
  108. ) = (
  109. Path(opt.save_dir),
  110. opt.epochs,
  111. opt.batch_size,
  112. opt.weights,
  113. opt.single_cls,
  114. opt.evolve,
  115. opt.data,
  116. opt.cfg,
  117. opt.resume,
  118. opt.noval,
  119. opt.nosave,
  120. opt.workers,
  121. opt.freeze,
  122. opt.mask_ratio,
  123. opt.is_train_on_platform
  124. )
  125. # callbacks.run('on_pretrain_routine_start')
  126. # Directories
  127. w = save_dir / "weights" # weights dir
  128. (w.parent if evolve else w).mkdir(parents=True, exist_ok=True) # make dir
  129. last, best = w / "last.pt", w / "best.pt"
  130. # Hyperparameters
  131. if isinstance(hyp, str):
  132. with open(hyp, errors="ignore") as f:
  133. hyp = yaml.safe_load(f) # load hyps dict
  134. LOGGER.info(colorstr("hyperparameters: ") + ", ".join(f"{k}={v}" for k, v in hyp.items()))
  135. opt.hyp = hyp.copy() # for saving hyps to checkpoints
  136. # Save run settings
  137. if not evolve:
  138. yaml_save(save_dir / "hyp.yaml", hyp)
  139. yaml_save(save_dir / "opt.yaml", vars(opt))
  140. TrainSdk.save_output_model(save_dir / "hyp.yaml")
  141. TrainSdk.save_output_model(save_dir / "opt.yaml")
  142. # Loggers
  143. data_dict = None
  144. if RANK in {-1, 0}:
  145. logger = GenericLogger(opt=opt, console_logger=LOGGER)
  146. # Config
  147. plots = not evolve and not opt.noplots # create plots
  148. overlap = not opt.no_overlap
  149. cuda = device.type != "cpu"
  150. init_seeds(opt.seed + 1 + RANK, deterministic=True)
  151. with torch_distributed_zero_first(LOCAL_RANK):
  152. data_dict = data_dict or check_dataset(data, is_train_on_platform) # check if None
  153. #训练训练无需train_path和val_path
  154. if not is_train_on_platform:
  155. train_path, val_path = data_dict["train"], data_dict["val"]
  156. nc = 1 if single_cls else int(data_dict["nc"]) # number of classes
  157. names = {0: "item"} if single_cls and len(data_dict["names"]) != 1 else data_dict["names"] # class names
  158. if is_train_on_platform:
  159. is_coco = False
  160. else:
  161. is_coco = isinstance(val_path, str) and val_path.endswith("coco/val2017.txt") # COCO dataset
  162. # Model
  163. check_suffix(weights, ".pt") # check weights
  164. pretrained = weights.endswith(".pt")
  165. if pretrained:
  166. with torch_distributed_zero_first(LOCAL_RANK):
  167. weights = attempt_download(weights) # download if not found locally
  168. ckpt = torch.load(weights, map_location="cpu") # load checkpoint to CPU to avoid CUDA memory leak
  169. model = SegmentationModel(cfg or ckpt["model"].yaml, ch=3, nc=nc, anchors=hyp.get("anchors")).to(device)
  170. exclude = ["anchor"] if (cfg or hyp.get("anchors")) and not resume else [] # exclude keys
  171. csd = ckpt["model"].float().state_dict() # checkpoint state_dict as FP32
  172. csd = intersect_dicts(csd, model.state_dict(), exclude=exclude) # intersect
  173. model.load_state_dict(csd, strict=False) # load
  174. LOGGER.info(f"Transferred {len(csd)}/{len(model.state_dict())} items from {weights}") # report
  175. else:
  176. model = SegmentationModel(cfg, ch=3, nc=nc, anchors=hyp.get("anchors")).to(device) # create
  177. amp = check_amp(model) # check AMP
  178. # Freeze
  179. freeze = [f"model.{x}." for x in (freeze if len(freeze) > 1 else range(freeze[0]))] # layers to freeze
  180. for k, v in model.named_parameters():
  181. v.requires_grad = True # train all layers
  182. # v.register_hook(lambda x: torch.nan_to_num(x)) # NaN to 0 (commented for erratic training results)
  183. if any(x in k for x in freeze):
  184. LOGGER.info(f"freezing {k}")
  185. v.requires_grad = False
  186. # Image size
  187. gs = max(int(model.stride.max()), 32) # grid size (max stride)
  188. imgsz = check_img_size(opt.imgsz, gs, floor=gs * 2) # verify imgsz is gs-multiple
  189. # Batch size
  190. if RANK == -1 and batch_size == -1: # single-GPU only, estimate best batch size
  191. batch_size = check_train_batch_size(model, imgsz, amp)
  192. logger.update_params({"batch_size": batch_size})
  193. # loggers.on_params_update({"batch_size": batch_size})
  194. # Optimizer
  195. nbs = 64 # nominal batch size
  196. accumulate = max(round(nbs / batch_size), 1) # accumulate loss before optimizing
  197. hyp["weight_decay"] *= batch_size * accumulate / nbs # scale weight_decay
  198. optimizer = smart_optimizer(model, opt.optimizer, hyp["lr0"], hyp["momentum"], hyp["weight_decay"])
  199. # Scheduler
  200. if opt.cos_lr:
  201. lf = one_cycle(1, hyp["lrf"], epochs) # cosine 1->hyp['lrf']
  202. else:
  203. lf = lambda x: (1 - x / epochs) * (1.0 - hyp["lrf"]) + hyp["lrf"] # linear
  204. scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) # plot_lr_scheduler(optimizer, scheduler, epochs)
  205. # EMA
  206. ema = ModelEMA(model) if RANK in {-1, 0} else None
  207. # Resume
  208. best_fitness, start_epoch = 0.0, 0
  209. if pretrained:
  210. if resume:
  211. best_fitness, start_epoch, epochs = smart_resume(ckpt, optimizer, ema, weights, epochs, resume)
  212. del ckpt, csd
  213. # DP mode
  214. if cuda and RANK == -1 and torch.cuda.device_count() > 1:
  215. LOGGER.warning(
  216. "WARNING ⚠️ DP not recommended, use torch.distributed.run for best DDP Multi-GPU results.\n"
  217. "See Multi-GPU Tutorial at https://docs.ultralytics.com/yolov5/tutorials/multi_gpu_training to get started."
  218. )
  219. model = torch.nn.DataParallel(model)
  220. # SyncBatchNorm
  221. if opt.sync_bn and cuda and RANK != -1:
  222. model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
  223. LOGGER.info("Using SyncBatchNorm()")
  224. if is_train_on_platform:
  225. # Trainloader
  226. train_loader, dataset = create_dataloader_platform(
  227. imgsz,
  228. batch_size // WORLD_SIZE,
  229. gs,
  230. single_cls,
  231. hyp=hyp,
  232. data_dict=data_dict,
  233. train_or_val_data='train',
  234. augment=True,
  235. cache=None if opt.cache == "val" else opt.cache,
  236. rect=opt.rect,
  237. rank=LOCAL_RANK,
  238. workers=workers,
  239. image_weights=opt.image_weights,
  240. quad=opt.quad,
  241. prefix=colorstr("train: "),
  242. shuffle=True,
  243. mask_downsample_ratio=mask_ratio,
  244. overlap_mask=overlap,
  245. )
  246. else:
  247. # Trainloader
  248. train_loader, dataset = create_dataloader(
  249. train_path,
  250. imgsz,
  251. batch_size // WORLD_SIZE,
  252. gs,
  253. single_cls,
  254. hyp=hyp,
  255. augment=True,
  256. cache=None if opt.cache == "val" else opt.cache,
  257. rect=opt.rect,
  258. rank=LOCAL_RANK,
  259. workers=workers,
  260. image_weights=opt.image_weights,
  261. quad=opt.quad,
  262. prefix=colorstr("train: "),
  263. shuffle=True,
  264. mask_downsample_ratio=mask_ratio,
  265. overlap_mask=overlap,
  266. )
  267. labels = np.concatenate(dataset.labels, 0)
  268. mlc = int(labels[:, 0].max()) # max label class
  269. assert mlc < nc, f"Label class {mlc} exceeds nc={nc} in {data}. Possible class labels are 0-{nc - 1}"
  270. # Process 0
  271. if RANK in {-1, 0}:
  272. if is_train_on_platform:
  273. val_loader = create_dataloader_platform(
  274. imgsz,
  275. batch_size // WORLD_SIZE * 2,
  276. gs,
  277. single_cls,
  278. hyp=hyp,
  279. data_dict=data_dict,
  280. train_or_val_data='val',
  281. cache=None if noval else opt.cache,
  282. rect=True,
  283. rank=-1,
  284. workers=workers * 2,
  285. pad=0.5,
  286. mask_downsample_ratio=mask_ratio,
  287. overlap_mask=overlap,
  288. prefix=colorstr("val: "),
  289. )[0]
  290. else:
  291. val_loader = create_dataloader(
  292. val_path,
  293. imgsz,
  294. batch_size // WORLD_SIZE * 2,
  295. gs,
  296. single_cls,
  297. hyp=hyp,
  298. cache=None if noval else opt.cache,
  299. rect=True,
  300. rank=-1,
  301. workers=workers * 2,
  302. pad=0.5,
  303. mask_downsample_ratio=mask_ratio,
  304. overlap_mask=overlap,
  305. prefix=colorstr("val: "),
  306. )[0]
  307. if not resume:
  308. if not opt.noautoanchor:
  309. check_anchors(dataset, model=model, thr=hyp["anchor_t"], imgsz=imgsz) # run AutoAnchor
  310. model.half().float() # pre-reduce anchor precision
  311. if plots:
  312. plot_labels(labels, names, save_dir)
  313. # callbacks.run('on_pretrain_routine_end', labels, names)
  314. # DDP mode
  315. if cuda and RANK != -1:
  316. model = smart_DDP(model)
  317. # Model attributes
  318. nl = de_parallel(model).model[-1].nl # number of detection layers (to scale hyps)
  319. hyp["box"] *= 3 / nl # scale to layers
  320. hyp["cls"] *= nc / 80 * 3 / nl # scale to classes and layers
  321. hyp["obj"] *= (imgsz / 640) ** 2 * 3 / nl # scale to image size and layers
  322. hyp["label_smoothing"] = opt.label_smoothing
  323. model.nc = nc # attach number of classes to model
  324. model.hyp = hyp # attach hyperparameters to model
  325. model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc # attach class weights
  326. model.names = names
  327. # Start training
  328. t0 = time.time()
  329. nb = len(train_loader) # number of batches
  330. nw = max(round(hyp["warmup_epochs"] * nb), 100) # number of warmup iterations, max(3 epochs, 100 iterations)
  331. # nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training
  332. last_opt_step = -1
  333. maps = np.zeros(nc) # mAP per class
  334. results = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls)
  335. scheduler.last_epoch = start_epoch - 1 # do not move
  336. scaler = torch.cuda.amp.GradScaler(enabled=amp)
  337. stopper, stop = EarlyStopping(patience=opt.patience), False
  338. compute_loss = ComputeLoss(model, overlap=overlap) # init loss class
  339. # callbacks.run('on_train_start')
  340. LOGGER.info(
  341. f'Image sizes {imgsz} train, {imgsz} val\n'
  342. f'Using {train_loader.num_workers * WORLD_SIZE} dataloader workers\n'
  343. f"Logging results to {colorstr('bold', save_dir)}\n"
  344. f'Starting training for {epochs} epochs...'
  345. )
  346. for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
  347. # callbacks.run('on_train_epoch_start')
  348. model.train()
  349. # Update image weights (optional, single-GPU only)
  350. if opt.image_weights:
  351. cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc # class weights
  352. iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights
  353. dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx
  354. # Update mosaic border (optional)
  355. # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
  356. # dataset.mosaic_border = [b - imgsz, -b] # height, width borders
  357. mloss = torch.zeros(4, device=device) # mean losses
  358. if RANK != -1:
  359. train_loader.sampler.set_epoch(epoch)
  360. pbar = enumerate(train_loader)
  361. LOGGER.info(
  362. ("\n" + "%11s" * 8)
  363. % ("Epoch", "GPU_mem", "box_loss", "seg_loss", "obj_loss", "cls_loss", "Instances", "Size")
  364. )
  365. if RANK in {-1, 0}:
  366. pbar = tqdm(pbar, total=nb, bar_format=TQDM_BAR_FORMAT) # progress bar
  367. optimizer.zero_grad()
  368. for i, (imgs, targets, paths, _, masks) in pbar: # batch ------------------------------------------------------
  369. # callbacks.run('on_train_batch_start')
  370. ni = i + nb * epoch # number integrated batches (since train start)
  371. imgs = imgs.to(device, non_blocking=True).float() / 255 # uint8 to float32, 0-255 to 0.0-1.0
  372. # Warmup
  373. if ni <= nw:
  374. xi = [0, nw] # x interp
  375. # compute_loss.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou)
  376. accumulate = max(1, np.interp(ni, xi, [1, nbs / batch_size]).round())
  377. for j, x in enumerate(optimizer.param_groups):
  378. # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
  379. x["lr"] = np.interp(ni, xi, [hyp["warmup_bias_lr"] if j == 0 else 0.0, x["initial_lr"] * lf(epoch)])
  380. if "momentum" in x:
  381. x["momentum"] = np.interp(ni, xi, [hyp["warmup_momentum"], hyp["momentum"]])
  382. # Multi-scale
  383. if opt.multi_scale:
  384. sz = random.randrange(int(imgsz * 0.5), int(imgsz * 1.5) + gs) // gs * gs # size
  385. sf = sz / max(imgs.shape[2:]) # scale factor
  386. if sf != 1:
  387. ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
  388. imgs = nn.functional.interpolate(imgs, size=ns, mode="bilinear", align_corners=False)
  389. # Forward
  390. with torch.cuda.amp.autocast(amp):
  391. pred = model(imgs) # forward
  392. loss, loss_items = compute_loss(pred, targets.to(device), masks=masks.to(device).float())
  393. if RANK != -1:
  394. loss *= WORLD_SIZE # gradient averaged between devices in DDP mode
  395. if opt.quad:
  396. loss *= 4.0
  397. # Backward
  398. scaler.scale(loss).backward()
  399. # Optimize - https://pytorch.org/docs/master/notes/amp_examples.html
  400. if ni - last_opt_step >= accumulate:
  401. scaler.unscale_(optimizer) # unscale gradients
  402. torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=10.0) # clip gradients
  403. scaler.step(optimizer) # optimizer.step
  404. scaler.update()
  405. optimizer.zero_grad()
  406. if ema:
  407. ema.update(model)
  408. last_opt_step = ni
  409. # Log
  410. if RANK in {-1, 0}:
  411. mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
  412. mem = f"{torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0:.3g}G" # (GB)
  413. pbar.set_description(
  414. ("%11s" * 2 + "%11.4g" * 6)
  415. % (f"{epoch}/{epochs - 1}", mem, *mloss, targets.shape[0], imgs.shape[-1])
  416. )
  417. # callbacks.run('on_train_batch_end', model, ni, imgs, targets, paths)
  418. # if callbacks.stop_training:
  419. # return
  420. # Mosaic plots
  421. if plots:
  422. if ni < 3:
  423. plot_images_and_masks(imgs, targets, masks, paths, save_dir / f"train_batch{ni}.jpg")
  424. if ni == 10:
  425. files = sorted(save_dir.glob("train*.jpg"))
  426. logger.log_images(files, "Mosaics", epoch)
  427. # end batch ------------------------------------------------------------------------------------------------
  428. # Scheduler
  429. lr = [x["lr"] for x in optimizer.param_groups] # for loggers
  430. scheduler.step()
  431. if RANK in {-1, 0}:
  432. # mAP
  433. # callbacks.run('on_train_epoch_end', epoch=epoch)
  434. ema.update_attr(model, include=["yaml", "nc", "hyp", "names", "stride", "class_weights"])
  435. final_epoch = (epoch + 1 == epochs) or stopper.possible_stop
  436. if not noval or final_epoch: # Calculate mAP
  437. results, maps, _ = validate.run(
  438. data_dict,
  439. batch_size=batch_size // WORLD_SIZE * 2,
  440. imgsz=imgsz,
  441. half=amp,
  442. model=ema.ema,
  443. single_cls=single_cls,
  444. dataloader=val_loader,
  445. save_dir=save_dir,
  446. plots=False,
  447. callbacks=callbacks,
  448. compute_loss=compute_loss,
  449. mask_downsample_ratio=mask_ratio,
  450. is_train_on_platform=is_train_on_platform,
  451. overlap=overlap,
  452. )
  453. # Update best mAP
  454. fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, mAP@.5, mAP@.5-.95]
  455. stop = stopper(epoch=epoch, fitness=fi) # early stop check
  456. if fi > best_fitness:
  457. best_fitness = fi
  458. log_vals = list(mloss) + list(results) + lr
  459. # callbacks.run('on_fit_epoch_end', log_vals, epoch, best_fitness, fi)
  460. # Log val metrics and media
  461. metrics_dict = dict(zip(KEYS, log_vals))
  462. logger.log_metrics(metrics_dict, epoch)
  463. # Save model
  464. if (not nosave) or (final_epoch and not evolve): # if save
  465. ckpt = {
  466. "epoch": epoch,
  467. "best_fitness": best_fitness,
  468. "model": deepcopy(de_parallel(model)).half(),
  469. "ema": deepcopy(ema.ema).half(),
  470. "updates": ema.updates,
  471. "optimizer": optimizer.state_dict(),
  472. "opt": vars(opt),
  473. "date": datetime.now().isoformat(),
  474. }
  475. # Save last, best and delete
  476. torch.save(ckpt, last)
  477. TrainSdk.save_output_model(last)
  478. if best_fitness == fi:
  479. torch.save(ckpt, best)
  480. TrainSdk.save_output_model(best)
  481. if opt.save_period > 0 and epoch % opt.save_period == 0:
  482. torch.save(ckpt, w / f"epoch{epoch}.pt")
  483. logger.log_model(w / f"epoch{epoch}.pt")
  484. TrainSdk.save_output_model(w / f"epoch{epoch}.pt")
  485. # 额外计算转成onnx模型的评价指标
  486. if is_train_on_platform:
  487. model2onnx(
  488. weights=w / f'epoch{epoch}.pt',
  489. imgsz=[opt.imgsz, opt.imgsz],
  490. batch_size=1,
  491. device="cpu",
  492. inplace=True,
  493. dynamic=False,
  494. simplify=False,
  495. opset=17
  496. )
  497. onnx_model = w / f"epoch{epoch}.onnx"
  498. TrainSdk.save_output_model(onnx_model)
  499. platform_data_args = data_dict["platform_data_args"]
  500. class_id_map_list = platform_data_args["class_id_map_list"]
  501. dll_file = platform_data_args["dll_file"]
  502. wrong_file = platform_data_args["wrong_file"]
  503. yolo_metas_yaml = platform_data_args['yolo_inst_seg_metas']
  504. metrics_type = platform_data_args['metrics_type']
  505. resize_mode = ResizeMode[platform_data_args['resize_mode']]
  506. seg_post_process_param = platform_data_args['seg_post_process_param']
  507. extra_contours_args = platform_data_args['extra_contours_args']
  508. needed_image_results_dict = val_loader.dataset.needed_image_results_dict
  509. needed_rois_dict = val_loader.dataset.needed_rois_dict
  510. yolo_inst_seg_metas = YoloInstanceSegMetas(
  511. yolo_type=YoloType[yolo_metas_yaml['yolo_type']],
  512. box_conf_thres=yolo_metas_yaml['box_conf_thres'],
  513. cls_conf_thres=yolo_metas_yaml['cls_conf_thres'],
  514. batch_size=yolo_metas_yaml['batch_size'],
  515. max_det=yolo_metas_yaml['max_det'],
  516. min_box_ratio=yolo_metas_yaml['min_box_ratio'],
  517. post_process_top_k=yolo_metas_yaml['post_process_top_k'],
  518. iou_fltth=yolo_metas_yaml['iou_fltth'],
  519. ios_fltth=yolo_metas_yaml['ios_fltth'],
  520. enable_iou_filt=yolo_metas_yaml['enable_iou_filt'],
  521. enable_ios_filt=yolo_metas_yaml['enable_ios_filt'],
  522. iou_fltth_diff_cls=yolo_metas_yaml['iou_fltth_diff_cls'],
  523. ios_fltth_diff_cls=yolo_metas_yaml['ios_fltth_diff_cls'],
  524. enable_iou_filt_diff_cls=yolo_metas_yaml['enable_iou_filt_diff_cls'],
  525. enable_ios_filt_diff_cls=yolo_metas_yaml['enable_iou_filt_diff_cls'],
  526. mask_thres=yolo_metas_yaml['mask_thres'],
  527. )
  528. for class_id_map in class_id_map_list:
  529. metric_reports = SegMetrics(is_local_file=False,
  530. files=val_loader.dataset.im_files,
  531. token=val_loader.dataset.token,
  532. onnx_file=onnx_model,
  533. resize_mode=resize_mode,
  534. needed_image_results_dict=needed_image_results_dict,
  535. needed_rois_dict=needed_rois_dict,
  536. extra_contours_args=extra_contours_args,
  537. class_id_map=class_id_map,
  538. wrong_file=wrong_file,
  539. dll_file=dll_file,
  540. yolo_inst_seg_metas=yolo_inst_seg_metas,
  541. seg_post_process_param=seg_post_process_param,
  542. use_contour_for_iou=True,
  543. metrics_type=metrics_type)
  544. metric_reports.run()
  545. del ckpt
  546. callbacks.run('on_model_save', last, epoch, final_epoch, best_fitness, fi)
  547. # EarlyStopping
  548. if RANK != -1: # if DDP training
  549. broadcast_list = [stop if RANK == 0 else None]
  550. dist.broadcast_object_list(broadcast_list, 0) # broadcast 'stop' to all ranks
  551. if RANK != 0:
  552. stop = broadcast_list[0]
  553. if stop:
  554. break # must break all DDP ranks
  555. # end epoch ----------------------------------------------------------------------------------------------------
  556. # end training -----------------------------------------------------------------------------------------------------
  557. if RANK in {-1, 0}:
  558. LOGGER.info(f"\n{epoch - start_epoch + 1} epochs completed in {(time.time() - t0) / 3600:.3f} hours.")
  559. for f in last, best:
  560. if f.exists():
  561. strip_optimizer(f) # strip optimizers
  562. if f is best:
  563. LOGGER.info(f"\nValidating {f}...")
  564. results, _, _ = validate.run(
  565. data_dict,
  566. batch_size=batch_size // WORLD_SIZE * 2,
  567. imgsz=imgsz,
  568. model=attempt_load(f, device).half(),
  569. iou_thres=0.65 if is_coco else 0.60, # best pycocotools at iou 0.65
  570. single_cls=single_cls,
  571. dataloader=val_loader,
  572. save_dir=save_dir,
  573. save_json=is_coco,
  574. verbose=True,
  575. plots=plots,
  576. callbacks=callbacks,
  577. compute_loss=compute_loss,
  578. mask_downsample_ratio=mask_ratio,
  579. overlap=overlap,
  580. ) # val best model with plots
  581. if is_coco:
  582. # callbacks.run('on_fit_epoch_end', list(mloss) + list(results) + lr, epoch, best_fitness, fi)
  583. metrics_dict = dict(zip(KEYS, list(mloss) + list(results) + lr))
  584. logger.log_metrics(metrics_dict, epoch)
  585. # callbacks.run('on_train_end', last, best, epoch, results)
  586. # on train end callback using genericLogger
  587. logger.log_metrics(dict(zip(KEYS[4:16], results)), epochs)
  588. if not opt.evolve:
  589. logger.log_model(best, epoch)
  590. if plots:
  591. plot_results_with_masks(file=save_dir / "results.csv") # save results.png
  592. files = ["results.png", "confusion_matrix.png", *(f"{x}_curve.png" for x in ("F1", "PR", "P", "R"))]
  593. files = [(save_dir / f) for f in files if (save_dir / f).exists()] # filter
  594. LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}")
  595. logger.log_images(files, "Results", epoch + 1)
  596. logger.log_images(sorted(save_dir.glob("val*.jpg")), "Validation", epoch + 1)
  597. torch.cuda.empty_cache()
  598. return results
  599. def parse_opt(known=False):
  600. """
  601. Parses command line arguments for training configurations, returning parsed arguments.
  602. Supports both known and unknown args.
  603. """
  604. parser = argparse.ArgumentParser()
  605. parser.add_argument("--weights", type=str, default=ROOT / "", help="initial weights path")
  606. parser.add_argument("--cfg", type=str, default=ROOT / "models/segment/yolov8-seg.yaml", help="model.yaml path")
  607. parser.add_argument("--data", type=str, default=ROOT / "data/vinno_data/Neck-Organ-Seg.yaml", help="dataset.yaml path")
  608. parser.add_argument("--hyp", type=str, default=ROOT / "data/hyps/hyp.scratch_neck-ogran.yaml", help="hyperparameters path")
  609. parser.add_argument("--epochs", type=int, default=100, help="total training epochs")
  610. parser.add_argument("--batch-size", type=int, default=16, help="total batch size for all GPUs, -1 for autobatch")
  611. parser.add_argument("--imgsz", "--img", "--img-size", type=int, default=320, help="train, val image size (pixels)")
  612. parser.add_argument("--rect", action="store_true", help="rectangular training")
  613. parser.add_argument("--resume", nargs="?", const=True, default=False, help="resume most recent training")
  614. parser.add_argument("--nosave", action="store_true", help="only save final checkpoint")
  615. parser.add_argument("--noval", action="store_true", help="only validate final epoch")
  616. parser.add_argument("--noautoanchor", action="store_true", help="disable AutoAnchor")
  617. parser.add_argument("--noplots", action="store_true", help="save no plot files")
  618. parser.add_argument("--evolve", type=int, nargs="?", const=300, help="evolve hyperparameters for x generations")
  619. parser.add_argument("--bucket", type=str, default="", help="gsutil bucket")
  620. parser.add_argument("--cache", type=str, nargs="?", const="ram", help="image --cache ram/disk")
  621. parser.add_argument("--image-weights", default=False, action="store_true", help="use weighted image selection for training")
  622. parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
  623. parser.add_argument("--multi-scale", action="store_true", help="vary img-size +/- 50%%")
  624. parser.add_argument("--single-cls", default=False, action="store_true", help="train multi-class data as single-class")
  625. parser.add_argument("--optimizer", type=str, choices=["SGD", "Adam", "AdamW"], default="SGD", help="optimizer")
  626. parser.add_argument("--sync-bn", action="store_true", help="use SyncBatchNorm, only available in DDP mode")
  627. parser.add_argument("--workers", type=int, default=1, help="max dataloader workers (per RANK in DDP mode)")
  628. parser.add_argument("--project", default=ROOT / "runs/train-seg", help="save to project/name")
  629. parser.add_argument("--name", default="exp", help="save to project/name")
  630. parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
  631. parser.add_argument("--quad", action="store_true", help="quad dataloader")
  632. parser.add_argument("--cos-lr", action="store_true", help="cosine LR scheduler")
  633. parser.add_argument("--label-smoothing", type=float, default=0.1, help="Label smoothing epsilon")
  634. parser.add_argument("--patience", type=int, default=100, help="EarlyStopping patience (epochs without improvement)")
  635. parser.add_argument("--freeze", nargs="+", type=int, default=[0], help="Freeze layers: backbone=10, first3=0 1 2")
  636. parser.add_argument("--save-period", type=int, default=10, help="Save checkpoint every x epochs (disabled if < 1)")
  637. parser.add_argument("--seed", type=int, default=0, help="Global training seed")
  638. parser.add_argument("--local_rank", type=int, default=-1, help="Automatic DDP Multi-GPU argument, do not modify")
  639. # Instance Segmentation Args
  640. parser.add_argument("--mask-ratio", type=int, default=1, help="Downsample the truth masks to saving memory")
  641. parser.add_argument("--no-overlap", action="store_true", help="Overlap masks train faster at slightly less mAP")
  642. # VINNO AI平台训练
  643. parser.add_argument('--is_train_on_platform', type=bool, default=True, help='True is train on platform,False is train on local')
  644. return parser.parse_known_args()[0] if known else parser.parse_args()
  645. def main(opt, callbacks=Callbacks()):
  646. """Initializes training or evolution of YOLOv5 models based on provided configuration and options."""
  647. if RANK in {-1, 0}:
  648. print_args(vars(opt))
  649. # check_git_status()
  650. # check_requirements(ROOT / "requirements.txt")
  651. # Resume
  652. if opt.resume and not opt.evolve: # resume from specified or most recent last.pt
  653. last = Path(check_file(opt.resume) if isinstance(opt.resume, str) else get_latest_run())
  654. opt_yaml = last.parent.parent / "opt.yaml" # train options yaml
  655. opt_data = opt.data # original dataset
  656. if opt_yaml.is_file():
  657. with open(opt_yaml, errors="ignore") as f:
  658. d = yaml.safe_load(f)
  659. else:
  660. d = torch.load(last, map_location="cpu")["opt"]
  661. opt = argparse.Namespace(**d) # replace
  662. opt.cfg, opt.weights, opt.resume = "", str(last), True # reinstate
  663. if is_url(opt_data):
  664. opt.data = check_file(opt_data) # avoid HUB resume auth timeout
  665. else:
  666. opt.data, opt.cfg, opt.hyp, opt.weights, opt.project = (
  667. check_file(opt.data),
  668. check_yaml(opt.cfg),
  669. check_yaml(opt.hyp),
  670. str(opt.weights),
  671. str(opt.project),
  672. ) # checks
  673. assert len(opt.cfg) or len(opt.weights), "either --cfg or --weights must be specified"
  674. if opt.evolve:
  675. if opt.project == str(ROOT / "runs/train-seg"): # if default project name, rename to runs/evolve-seg
  676. opt.project = str(ROOT / "runs/evolve-seg")
  677. opt.exist_ok, opt.resume = opt.resume, False # pass resume to exist_ok and disable resume
  678. if opt.name == "cfg":
  679. opt.name = Path(opt.cfg).stem # use model.yaml as name
  680. opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))
  681. # DDP mode
  682. device = select_device(opt.device, batch_size=opt.batch_size)
  683. if LOCAL_RANK != -1:
  684. msg = "is not compatible with YOLOv5 Multi-GPU DDP training"
  685. assert not opt.image_weights, f"--image-weights {msg}"
  686. assert not opt.evolve, f"--evolve {msg}"
  687. assert opt.batch_size != -1, f"AutoBatch with --batch-size -1 {msg}, please pass a valid --batch-size"
  688. assert opt.batch_size % WORLD_SIZE == 0, f"--batch-size {opt.batch_size} must be multiple of WORLD_SIZE"
  689. assert torch.cuda.device_count() > LOCAL_RANK, "insufficient CUDA devices for DDP command"
  690. torch.cuda.set_device(LOCAL_RANK)
  691. device = torch.device("cuda", LOCAL_RANK)
  692. dist.init_process_group(backend="nccl" if dist.is_nccl_available() else "gloo")
  693. # Train
  694. if not opt.evolve:
  695. train(opt.hyp, opt, device, callbacks)
  696. # Evolve hyperparameters (optional)
  697. else:
  698. # Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit)
  699. meta = {
  700. "lr0": (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3)
  701. "lrf": (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf)
  702. "momentum": (0.3, 0.6, 0.98), # SGD momentum/Adam beta1
  703. "weight_decay": (1, 0.0, 0.001), # optimizer weight decay
  704. "warmup_epochs": (1, 0.0, 5.0), # warmup epochs (fractions ok)
  705. "warmup_momentum": (1, 0.0, 0.95), # warmup initial momentum
  706. "warmup_bias_lr": (1, 0.0, 0.2), # warmup initial bias lr
  707. "box": (1, 0.02, 0.2), # box loss gain
  708. "cls": (1, 0.2, 4.0), # cls loss gain
  709. "cls_pw": (1, 0.5, 2.0), # cls BCELoss positive_weight
  710. "obj": (1, 0.2, 4.0), # obj loss gain (scale with pixels)
  711. "obj_pw": (1, 0.5, 2.0), # obj BCELoss positive_weight
  712. "iou_t": (0, 0.1, 0.7), # IoU training threshold
  713. "anchor_t": (1, 2.0, 8.0), # anchor-multiple threshold
  714. "anchors": (2, 2.0, 10.0), # anchors per output grid (0 to ignore)
  715. "fl_gamma": (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5)
  716. "hsv_h": (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction)
  717. "hsv_s": (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction)
  718. "hsv_v": (1, 0.0, 0.9), # image HSV-Value augmentation (fraction)
  719. "degrees": (1, 0.0, 45.0), # image rotation (+/- deg)
  720. "translate": (1, 0.0, 0.9), # image translation (+/- fraction)
  721. "scale": (1, 0.0, 0.9), # image scale (+/- gain)
  722. "shear": (1, 0.0, 10.0), # image shear (+/- deg)
  723. "perspective": (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001
  724. "flipud": (1, 0.0, 1.0), # image flip up-down (probability)
  725. "fliplr": (0, 0.0, 1.0), # image flip left-right (probability)
  726. "mosaic": (1, 0.0, 1.0), # image mixup (probability)
  727. "mixup": (1, 0.0, 1.0), # image mixup (probability)
  728. "copy_paste": (1, 0.0, 1.0),
  729. } # segment copy-paste (probability)
  730. with open(opt.hyp, errors="ignore") as f:
  731. hyp = yaml.safe_load(f) # load hyps dict
  732. if "anchors" not in hyp: # anchors commented in hyp.yaml
  733. hyp["anchors"] = 3
  734. if opt.noautoanchor:
  735. del hyp["anchors"], meta["anchors"]
  736. opt.noval, opt.nosave, save_dir = True, True, Path(opt.save_dir) # only val/save final epoch
  737. # ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices
  738. evolve_yaml, evolve_csv = save_dir / "hyp_evolve.yaml", save_dir / "evolve.csv"
  739. if opt.bucket:
  740. # download evolve.csv if exists
  741. subprocess.run(
  742. [
  743. "gsutil",
  744. "cp",
  745. f"gs://{opt.bucket}/evolve.csv",
  746. str(evolve_csv),
  747. ]
  748. )
  749. for _ in range(opt.evolve): # generations to evolve
  750. if evolve_csv.exists(): # if evolve.csv exists: select best hyps and mutate
  751. # Select parent(s)
  752. parent = "single" # parent selection method: 'single' or 'weighted'
  753. x = np.loadtxt(evolve_csv, ndmin=2, delimiter=",", skiprows=1)
  754. n = min(5, len(x)) # number of previous results to consider
  755. x = x[np.argsort(-fitness(x))][:n] # top n mutations
  756. w = fitness(x) - fitness(x).min() + 1e-6 # weights (sum > 0)
  757. if parent == "single" or len(x) == 1:
  758. # x = x[random.randint(0, n - 1)] # random selection
  759. x = x[random.choices(range(n), weights=w)[0]] # weighted selection
  760. elif parent == "weighted":
  761. x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
  762. # Mutate
  763. mp, s = 0.8, 0.2 # mutation probability, sigma
  764. npr = np.random
  765. npr.seed(int(time.time()))
  766. g = np.array([meta[k][0] for k in hyp.keys()]) # gains 0-1
  767. ng = len(meta)
  768. v = np.ones(ng)
  769. while all(v == 1): # mutate until a change occurs (prevent duplicates)
  770. v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
  771. for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
  772. hyp[k] = float(x[i + 12] * v[i]) # mutate
  773. # Constrain to limits
  774. for k, v in meta.items():
  775. hyp[k] = max(hyp[k], v[1]) # lower limit
  776. hyp[k] = min(hyp[k], v[2]) # upper limit
  777. hyp[k] = round(hyp[k], 5) # significant digits
  778. # Train mutation
  779. results = train(hyp.copy(), opt, device, callbacks)
  780. callbacks = Callbacks()
  781. # Write mutation results
  782. print_mutation(KEYS[4:16], results, hyp.copy(), save_dir, opt.bucket)
  783. # Plot results
  784. plot_evolve(evolve_csv)
  785. LOGGER.info(
  786. f'Hyperparameter evolution finished {opt.evolve} generations\n'
  787. f"Results saved to {colorstr('bold', save_dir)}\n"
  788. f'Usage example: $ python train.py --hyp {evolve_yaml}'
  789. )
  790. def run(**kwargs):
  791. """
  792. Executes YOLOv5 training with given parameters, altering options programmatically; returns updated options.
  793. Example: mport train; train.run(data='coco128.yaml', imgsz=320, weights='yolov5m.pt')
  794. """
  795. opt = parse_opt(True)
  796. for k, v in kwargs.items():
  797. setattr(opt, k, v)
  798. main(opt)
  799. return opt
  800. if __name__ == "__main__":
  801. # from wrongfile.neck_organ.datagenerate_thyroidorgan import date_generate
  802. #
  803. # # token = "4925EC4929684AA0ABB0173B03CFC8FF"
  804. # token = "4925EC4929684AA0ABB0173B03CFC8FF"
  805. # yaml_name = "organ-seg"
  806. # wrong_names = "wrongname.txt"
  807. #
  808. # #需要和yaml中的index对应
  809. # title_dict= {
  810. # "甲状腺横切":0,
  811. # "甲状腺纵切":0,
  812. # "颈动脉短轴": 1,
  813. # "颈动脉长轴": 1,
  814. # "颈部气管":2
  815. # }
  816. # use_image_title = ["无可标项"]
  817. #
  818. # date_generate(token, yaml_name, wrong_names, title_dict, use_image_title)
  819. opt = parse_opt()
  820. main(opt)