File size: 6,341 Bytes
4c01f30 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | """Custom YOLOv8 Training & Export Script for E-Waste Cannibalization Index.
Supports training on local splits (`splits/data.yaml`), Hugging Face dataset structures,
and exporting quantized TFLite INT8 models.
"""
from __future__ import annotations
import argparse
import json
import logging
import os
import sys
from pathlib import Path
import yaml
from ultralytics import YOLO
# Enforce all cache and runs directories to reside strictly within workspace
workspace_dir = Path(__file__).resolve().parent.parent
cache_dir = (workspace_dir / "data" / "cache").resolve()
cache_dir.mkdir(parents=True, exist_ok=True)
runs_dir = (workspace_dir / "data" / "runs").resolve()
runs_dir.mkdir(parents=True, exist_ok=True)
os.environ["TORCH_HOME"] = str(cache_dir)
os.environ["HF_HOME"] = str(cache_dir)
os.environ["ULTRALYTICS_CONFIG_DIR"] = str(cache_dir)
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
log = logging.getLogger(__name__)
CONFIG_PATH = workspace_dir / "training" / "train_config.yaml"
def load_train_config(config_file: Path = CONFIG_PATH) -> dict:
if config_file.exists():
with open(config_file, "r", encoding="utf-8") as f:
return yaml.safe_load(f)
return {
"data": "splits/data.yaml",
"model": "yolov8n.pt",
"imgsz": 960,
"epochs": 50,
"batch": 8,
"copy_paste": 0.8,
"cls": 2.5,
}
def run_training(config_override: dict | None = None, push_model_repo: str | None = None) -> dict:
cfg = load_train_config()
if config_override:
cfg.update(config_override)
log.info("Loaded training configuration: %s", cfg)
model_name = cfg.get("model", "yolov8n.pt")
# Resolve dataset yaml path
raw_data_path = cfg.get("data", "splits/data.yaml")
data_path_obj = Path(raw_data_path)
if not data_path_obj.is_absolute():
data_path_obj = (workspace_dir / raw_data_path).resolve()
if not data_path_obj.exists():
hf_dataset_yaml = workspace_dir / "huggingface_dataset" / "data.yaml"
if hf_dataset_yaml.exists():
data_path_obj = hf_dataset_yaml.resolve()
data_yaml = str(data_path_obj)
epochs = int(cfg.get("epochs", 50))
imgsz = int(cfg.get("imgsz", 960))
batch_size = int(cfg.get("batch", 8))
log.info("Initializing YOLO model backbone: %s", model_name)
model = YOLO(model_name)
# Train model with Copy-Paste synthetic augmentation and elevated class loss gain
log.info("Starting YOLOv8 fine-tuning on %s (%d epochs, imgsz=%d)...", data_yaml, epochs, imgsz)
results = model.train(
data=data_yaml,
epochs=epochs,
imgsz=imgsz,
batch=batch_size,
copy_paste=float(cfg.get("copy_paste", 0.8)),
mosaic=float(cfg.get("mosaic", 1.0)),
mixup=float(cfg.get("mixup", 0.15)),
box=float(cfg.get("box", 7.5)),
cls=float(cfg.get("cls", 2.5)),
dfl=float(cfg.get("dfl", 1.5)),
project=str(runs_dir),
name="ewaste_purity_v1",
exist_ok=True,
verbose=True,
)
# Validate trained model on test split
log.info("Validating trained model on test split...")
metrics = model.val(data=data_yaml, split="test", imgsz=imgsz)
maps_per_class = metrics.box.maps.tolist() if hasattr(metrics.box, "maps") else []
mp = float(metrics.box.mp) if hasattr(metrics.box, "mp") else 0.0
mr = float(metrics.box.mr) if hasattr(metrics.box, "mr") else 0.0
map50 = float(metrics.box.map50) if hasattr(metrics.box, "map50") else 0.0
map95 = float(metrics.box.map) if hasattr(metrics.box, "map") else 0.0
eval_summary = {
"mean_precision": round(mp, 4),
"mean_recall": round(mr, 4),
"mAP_50": round(map50, 4),
"mAP_50_95": round(map95, 4),
"maps_per_class": maps_per_class,
}
eval_file = workspace_dir / "reports" / "model_eval_summary.json"
eval_file.parent.mkdir(parents=True, exist_ok=True)
eval_file.write_text(json.dumps(eval_summary, indent=2), encoding="utf-8")
log.info("Saved evaluation summary to %s", eval_file)
# Export model to INT8 TFLite format
try:
log.info("Exporting trained model to TFLite format...")
model.export(format="tflite", int8=True, imgsz=imgsz)
log.info("TFLite export successful!")
except Exception as exc:
log.warning("TFLite export deferred: %s", exc)
# Optional model upload to Hugging Face Hub
if push_model_repo:
try:
from huggingface_hub import HfApi
api = HfApi()
api.create_repo(repo_id=push_model_repo, repo_type="model", exist_ok=True)
best_weights = runs_dir / "ewaste_purity_v1" / "weights" / "best.pt"
if best_weights.exists():
api.upload_file(
path_or_fileobj=str(best_weights),
path_in_repo="model.pt",
repo_id=push_model_repo,
repo_type="model",
)
log.info("Uploaded best model weights to Hugging Face Hub: %s", push_model_repo)
except Exception as exc:
log.warning("Could not upload model to Hugging Face Hub: %s", exc)
return eval_summary
def main():
parser = argparse.ArgumentParser(description="Custom YOLOv8 Training Script for E-Waste Cannibalization Index")
parser.add_argument("-e", "--epochs", type=int, default=50, help="Number of training epochs")
parser.add_argument("-b", "--batch", type=int, default=8, help="Training batch size")
parser.add_argument("-i", "--imgsz", type=int, default=960, help="Input image size")
parser.add_argument("-m", "--model", type=str, default="yolov8n.pt", help="YOLOv8 backbone model")
parser.add_argument("-d", "--data", type=str, default="splits/data.yaml", help="Path to data.yaml specification")
parser.add_argument("--push-model-to-hf", type=str, help="HF Hub model repository ID to upload trained weights")
args = parser.parse_args()
override = {
"epochs": args.epochs,
"batch": args.batch,
"imgsz": args.imgsz,
"model": args.model,
"data": args.data,
}
run_training(override, push_model_repo=args.push_model_to_hf)
if __name__ == "__main__":
main()
|