Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions agent_docs/ml-pipeline.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,8 @@ labels in `ml/real_data/labels/`.
## Training Harness
`ml/train.py` runs on CPU, one GPU or DDP with the same command (`--device cpu | auto | 0 | 0,1,2,3`); `--workers` defaults to the usable CPU count (max 8) and `--batch` is the total across GPUs (default: 16 per device).
Presets: `smoke` (2 epochs, yolov8n, imgsz 320), `stage-a` (synthetic pretrain, yolov8s, imgsz 960, 100 epochs), `stage-b` (mixed fine-tune from the stage-A `best.pt` via `--model`, real images repeated `--real-oversample` times through `--real-train DIR`, lr0 0.002).
Always pretrained weights; `--resume RUN_DIR` continues an interrupted run; `--dry-run` prints the resolved plan (device layout, batch per process, dataset counts, class-vocabulary check against `ml/classes.yaml`) without importing torch.
Each run folder (`ml/experiments/run_*`, gitignored) holds `config.yaml`, `notes.md`, `best.pt`, `best.onnx` and `metrics.json` (per-class P/R/F1/AP/accuracy, the F1/accuracy gate verdict, environment, dataset counts).
Always pretrained weights; `--resume RUN_DIR` continues an interrupted run (it keeps the run's base model, total batch and rebuilt mixed/oversampled dataset, and `metrics.json` records `resumed_from`); `--dry-run` prints the resolved plan (device layout, batch per process, dataset counts, class-vocabulary check against `ml/classes.yaml`) without importing torch.
Each run folder (`ml/experiments/run_*`, gitignored) holds `config.yaml`, `notes.md`, `best.pt`, `best.onnx` and `metrics.json` (per-class P/R/F1/AP/accuracy, the F1/accuracy gate verdict, environment, dataset counts and the effective `data_effective` yaml).
`ml/kaggle/train_kaggle.py` is the self-contained Kaggle twin (installs ultralytics, finds `data.yaml` under `/kaggle/input`, writes the same artifacts to `/kaggle/working/digisim_run`); `ml/tests/test_train_harness.py` keeps its preset table equal to `train.py`.
`ml/make_smoke_dataset.py` writes a throwaway procedural dataset for harness checks (not training data). Harness tests: `cd ml && uv run pytest` (add `DIGISIM_ML_SMOKE=1` for the 2-epoch CPU run).

Expand Down
14 changes: 9 additions & 5 deletions ml/kaggle/train_kaggle.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,14 +397,15 @@ def build_plan(args: argparse.Namespace) -> dict[str, Any]:
out_dir = resume.parent.parent.parent if resume else args.out
saved = read_yaml(out_dir / "config.yaml") if resume and (out_dir / "config.yaml").is_file() else {}
preset = PRESETS[args.preset or str(saved.get("preset") or "stage-a")]
model = str(resume) if resume else (args.model or preset.model)
model = str(saved.get("model") or resume) if resume else (args.model or preset.model) # a resumed run keeps its original base weights on record
if model is None:
raise ValueError(f"preset {preset.name} fine-tunes earlier weights: pass --model /kaggle/input/<stage-a>/best.pt")
saved_real = saved.get("real_train") or []
real_train = [Path(str(p)) for p in (args.real_train or saved_real)]
inherited = not args.real_train and bool(saved_real)
default_oversample = int(saved.get("real_oversample") or 1) if inherited else (preset.real_oversample if real_train else 1)
oversample = args.real_oversample if args.real_oversample is not None else default_oversample
saved_batch = int(str(saved["batch_total"])) if resume and saved.get("batch_total") else None # resume keeps the original total batch unless --batch says otherwise
if oversample > 1 and not real_train:
raise ValueError("--real-oversample needs at least one --real-train folder")
warnings: list[str] = []
Expand All @@ -424,7 +425,7 @@ def build_plan(args: argparse.Namespace) -> dict[str, Any]:
"device": device_spec(ids),
"world_size": world,
"ddp": world > 1,
"batch_total": resolve_batch(args.batch, preset.batch_per_device, world),
"batch_total": resolve_batch(args.batch if args.batch is not None else saved_batch, preset.batch_per_device, world),
"workers": args.workers if args.workers is not None else default_workers(),
"epochs": args.epochs if args.epochs is not None else int(saved.get("epochs") or preset.epochs),
"imgsz": args.imgsz if args.imgsz is not None else int(saved.get("imgsz") or preset.imgsz),
Expand Down Expand Up @@ -469,9 +470,11 @@ def run(plan: dict[str, Any], install: bool) -> Path:
(out / "config.yaml").write_text(yaml.safe_dump({**plan, "data_effective": str(data_yaml)}, sort_keys=False))

started = time.time()
model = YOLO(plan["model"]) # always a pretrained checkpoint: transfer learning only
model = YOLO(plan["resume"] or plan["model"]) # always a pretrained checkpoint: transfer learning only
if plan["resume"]:
model.train(resume=True, device=plan["device"], batch=plan["batch_total"], imgsz=plan["imgsz"], workers=plan["workers"])
# `data` is only ultralytics' fallback when the checkpoint's recorded dataset yaml is gone (copied run dir); without it a
# resume silently falls back to coco8 instead of the mixed, oversampled dataset.
model.train(resume=True, data=str(data_yaml), device=plan["device"], batch=plan["batch_total"], imgsz=plan["imgsz"], workers=plan["workers"])
else:
model.train(
data=str(data_yaml),
Expand Down Expand Up @@ -506,6 +509,7 @@ def run(plan: dict[str, Any], install: bool) -> Path:
"schema_version": METRICS_SCHEMA_VERSION,
"run_name": out.name,
"preset": plan["preset"],
"resumed_from": plan["resume"],
"map50": float(val.box.map50),
"map50_95": float(val.box.map),
"mean_precision": float(val.box.mp),
Expand All @@ -514,7 +518,7 @@ def run(plan: dict[str, Any], install: bool) -> Path:
"per_class": per_class,
"gate": gate_verdict(per_class),
"class_names": [best_model.names[i] for i in sorted(best_model.names)],
"dataset": {"data": plan["data_yaml"], **{f"{k}_images": v for k, v in counts.items()}, "real_oversample": plan["real_oversample"]},
"dataset": {"data": plan["data_yaml"], "data_effective": str(data_yaml), **{f"{k}_images": v for k, v in counts.items()}, "real_oversample": plan["real_oversample"]},
"settings": {k: plan[k] for k in ("model", "epochs", "imgsz", "device", "workers", "seed", "lr0")} | {"batch": plan["batch_total"]},
"environment": environment_info(),
"train_seconds": round(time.time() - started, 1),
Expand Down
107 changes: 107 additions & 0 deletions ml/tests/test_train_harness.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,60 @@ def test_resume_keeps_real_oversampling(fake_yolo: type[FakeYOLO], smoke_data: P
assert json.loads((run_dir / "metrics.json").read_text())["dataset"]["real_oversample"] == 4


def test_resume_of_relocated_mixed_run_keeps_data_config_and_metrics(fake_yolo: type[FakeYOLO], monkeypatch: pytest.MonkeyPatch, smoke_data: Path, real_images: Path, tmp_path: Path) -> None:
"""
Resuming a stage-B mixed run whose folder moved still trains on the oversampled mix and records the true config and metrics.

ultralytics resumes on the dataset yaml stored in the checkpoint and, when that file is gone, on whatever `data` the resume
call passes (its default is coco8). The fake below reproduces exactly that rule.
"""
loaded: list[str] = []

class RecordingYOLO(FakeYOLO):
"""FakeYOLO that also remembers which weights each YOLO() call loaded."""

def __init__(self, weights: str) -> None:
"""
Record the requested weights.

Args:
weights: Checkpoint path or name the harness asked for.
"""
super().__init__(weights)
loaded.append(weights)

monkeypatch.setattr(sys.modules["ultralytics"], "YOLO", RecordingYOLO)
mixed_run = ["--data", str(smoke_data), "--real-train", str(real_images), "--batch", "8", "--device", "cpu", "--project", str(tmp_path / "runs"), "--name", "b"]
first = parse(["--preset", "stage-b", "--model", "stage_a_best.pt", *mixed_run])
run_dir = train.train(first)
original_lines = (run_dir / "train_mixed.txt").read_text().split()
original_data = Path(str(kinds(fake_yolo, "train")[0]["data"]))
assert original_data == run_dir / "data_mixed.yaml"
first_metrics = json.loads((run_dir / "metrics.json").read_text())
(run_dir / "train" / "weights").mkdir(parents=True)
(run_dir / "train" / "weights" / "last.pt").write_bytes(b"pt") # the interrupt left a checkpoint behind
moved = tmp_path / "moved" / "b"
moved.parent.mkdir()
run_dir.rename(moved)

resumed = parse(["--resume", str(moved), "--device", "cpu"])
train.train(resumed)

resume_call = kinds(fake_yolo, "train")[1]
assert resume_call["resume"] is True and loaded[2] == str(moved / "train" / "weights" / "last.pt")
effective = original_data if original_data.exists() else Path(str(resume_call.get("data", "coco8.yaml"))) # ultralytics' check_resume rule
assert effective == moved / "data_mixed.yaml"
assert (moved / "train_mixed.txt").read_text().split() == original_lines
assert original_lines.count(str((real_images / "real_0.jpg").resolve())) == 4
saved = yaml.safe_load((moved / "config.yaml").read_text())
assert (saved["model"], saved["batch"], saved["real_oversample"], saved["real_train"]) == ("stage_a_best.pt", 8, 4, [str(real_images)])
assert saved["resume"] == str(moved / "train" / "weights" / "last.pt") and saved["data_effective"] == str(moved / "data_mixed.yaml")
metrics = json.loads((moved / "metrics.json").read_text())
assert metrics["resumed_from"] == saved["resume"] and metrics["dataset"]["data_effective"] == saved["data_effective"]
assert (metrics["settings"]["model"], metrics["settings"]["batch"], metrics["dataset"]["real_oversample"]) == ("stage_a_best.pt", 8, 4)
assert first_metrics["resumed_from"] is None


def test_kaggle_resume_keeps_real_oversampling(fake_yolo: type[FakeYOLO], smoke_data: Path, real_images: Path, tmp_path: Path) -> None:
"""The Kaggle twin restores the saved mix on --resume and never rewrites data.yaml without the oversampled train list."""
out = tmp_path / "kaggle"
Expand All @@ -302,6 +356,59 @@ def test_kaggle_resume_keeps_real_oversampling(fake_yolo: type[FakeYOLO], smoke_
assert json.loads((out / "metrics.json").read_text())["dataset"]["real_oversample"] == 4


def test_kaggle_resume_of_relocated_mixed_run_keeps_data_config_and_metrics(fake_yolo: type[FakeYOLO], monkeypatch: pytest.MonkeyPatch, smoke_data: Path, real_images: Path, tmp_path: Path) -> None:
"""
Resuming a copied Kaggle stage-B run still trains on the oversampled mix and records the true config and metrics.

ultralytics resumes on the dataset yaml stored in the checkpoint and, when that file is gone, on whatever `data` the resume
call passes (its default is coco8). The fake below reproduces exactly that rule.
"""
loaded: list[str] = []

class RecordingYOLO(FakeYOLO):
"""FakeYOLO that also remembers which weights each YOLO() call loaded."""

def __init__(self, weights: str) -> None:
"""
Record the requested weights.

Args:
weights: Checkpoint path or name the harness asked for.
"""
super().__init__(weights)
loaded.append(weights)

monkeypatch.setattr(sys.modules["ultralytics"], "YOLO", RecordingYOLO)
parser = train_kaggle.build_parser()
mixed_run = ["--data", str(smoke_data), "--real-train", str(real_images), "--batch", "8", "--device", "cpu", "--out", str(tmp_path / "kaggle")]
first = train_kaggle.build_plan(parser.parse_args(["--preset", "stage-b", "--model", "stage_a_best.pt", *mixed_run]))
out = train_kaggle.run(first, install=False)
original_lines = (out / "train_mixed.txt").read_text().split()
original_data = Path(str(kinds(fake_yolo, "train")[0]["data"]))
assert original_data == out / "data.yaml"
(out / "train" / "weights").mkdir(parents=True)
(out / "train" / "weights" / "last.pt").write_bytes(b"pt") # the interrupt left a checkpoint behind
moved = tmp_path / "moved" / "kaggle"
moved.parent.mkdir()
out.rename(moved)

plan = train_kaggle.build_plan(parser.parse_args(["--resume", str(moved), "--device", "cpu"]))
train_kaggle.run(plan, install=False)

resume_call = kinds(fake_yolo, "train")[1]
last = str(moved / "train" / "weights" / "last.pt")
assert resume_call["resume"] is True and loaded[2] == last
effective = original_data if original_data.exists() else Path(str(resume_call.get("data", "coco8.yaml"))) # ultralytics' check_resume rule
assert effective == moved / "data.yaml"
assert (moved / "train_mixed.txt").read_text().split() == original_lines
saved = yaml.safe_load((moved / "config.yaml").read_text())
assert (saved["model"], saved["batch_total"], saved["real_oversample"], saved["real_train"]) == ("stage_a_best.pt", 8, 4, [str(real_images)])
assert saved["resume"] == last and saved["data_effective"] == str(moved / "data.yaml")
metrics = json.loads((moved / "metrics.json").read_text())
assert metrics["resumed_from"] == last and metrics["dataset"]["data_effective"] == saved["data_effective"]
assert (metrics["settings"]["model"], metrics["settings"]["batch"], metrics["dataset"]["real_oversample"]) == ("stage_a_best.pt", 8, 4)


def test_kaggle_cli_ignores_only_the_jupyter_kernel_arguments(smoke_data: Path, capsys: pytest.CaptureFixture[str]) -> None:
"""`-f kernel.json` is dropped, but a mistyped option fails loudly instead of silently starting the wrong run."""
assert train_kaggle.strip_kernel_args(["--device", "cpu", "-f", "/tmp/kernel.json", "--dry-run"]) == ["--device", "cpu", "--dry-run"]
Expand Down
15 changes: 10 additions & 5 deletions ml/train.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,14 +419,15 @@ def resolve_config(args: argparse.Namespace) -> TrainConfig:
resume = resolve_resume_checkpoint(args.resume) if args.resume else None
saved = load_saved_config(resume.parent.parent.parent) if resume else {}
preset = PRESETS[args.preset or str(saved.get("preset") or DEFAULT_PRESET)]
model = str(resume) if resume else (args.model or preset.model)
model = str(saved.get("model") or resume) if resume else (args.model or preset.model) # a resumed run keeps its original base weights on record
if model is None:
raise ValueError(f"preset {preset.name} fine-tunes earlier weights: pass --model path/to/stage_a/best.pt")
saved_real = [Path(str(p)) for p in saved.get("real_train") or []]
real_train = tuple(args.real_train or saved_real)
inherited = not args.real_train and bool(saved_real)
default_oversample = int(saved.get("real_oversample") or 1) if inherited else (preset.real_oversample if real_train else 1)
oversample = args.real_oversample if args.real_oversample is not None else default_oversample
saved_batch = int(str(saved["batch"])) if resume and saved.get("batch") else None # resume keeps the original total batch unless --batch says otherwise
if oversample > 1 and not real_train:
raise ValueError("--real-oversample needs at least one --real-train folder")
return TrainConfig(
Expand All @@ -437,7 +438,7 @@ def resolve_config(args: argparse.Namespace) -> TrainConfig:
name=resume.parent.parent.parent.name if resume else (args.name or f"run_{datetime.now():%Y%m%d_%H%M}"),
epochs=args.epochs if args.epochs is not None else int(saved.get("epochs") or preset.epochs),
imgsz=args.imgsz if args.imgsz is not None else int(saved.get("imgsz") or preset.imgsz),
batch=resolve_batch(args.batch, preset.batch_per_device, plan),
batch=resolve_batch(args.batch if args.batch is not None else saved_batch, preset.batch_per_device, plan),
device=plan,
workers=args.workers if args.workers is not None else default_workers(),
patience=args.patience if args.patience is not None else int(saved.get("patience") or preset.patience),
Expand Down Expand Up @@ -620,7 +621,7 @@ def train(cfg: TrainConfig) -> Path:
(run_dir / "notes.md").write_text(f"# {cfg.name}\n\n{cfg.notes or 'No notes provided.'}\n")

started = time.time()
model = YOLO(cfg.model) # always a pretrained checkpoint: transfer learning only
model = YOLO(str(cfg.resume) if cfg.resume else cfg.model) # always a pretrained checkpoint: transfer learning only
train_kwargs: dict[str, object] = {
"data": str(data_yaml),
"epochs": cfg.epochs,
Expand All @@ -640,8 +641,10 @@ def train(cfg: TrainConfig) -> Path:
"exist_ok": True,
}
if cfg.resume:
# ultralytics keeps the original run settings from the checkpoint and only lets these be overridden.
model.train(resume=True, device=cfg.device.spec, batch=cfg.batch, imgsz=cfg.imgsz, workers=cfg.workers)
# ultralytics keeps the original run settings from the checkpoint and only lets the overrides below be changed. `data` is
# only its fallback for a checkpoint whose recorded dataset yaml no longer exists (moved run dir); without it ultralytics
# silently resumes on its default coco8 instead of the mixed, oversampled dataset.
model.train(resume=True, data=str(data_yaml), device=cfg.device.spec, batch=cfg.batch, imgsz=cfg.imgsz, workers=cfg.workers)
else:
model.train(**train_kwargs)
trainer = model.trainer
Expand Down Expand Up @@ -672,6 +675,7 @@ def train(cfg: TrainConfig) -> Path:
"schema_version": METRICS_SCHEMA_VERSION,
"run_name": cfg.name,
"preset": cfg.preset,
"resumed_from": str(cfg.resume) if cfg.resume else None,
"map50": float(val.box.map50),
"map50_95": float(val.box.map),
"mean_precision": float(val.box.mp),
Expand All @@ -682,6 +686,7 @@ def train(cfg: TrainConfig) -> Path:
"class_names": [best_model.names[i] for i in sorted(best_model.names)],
"dataset": {
"data": str(cfg.data),
"data_effective": str(data_yaml),
"train_images": len(split_images(data_cfg, cfg.data, "train")),
"val_images": len(split_images(data_cfg, cfg.data, "val")),
"test_images": len(split_images(data_cfg, cfg.data, "test")),
Expand Down
Loading