diff --git a/agent_docs/ml-pipeline.md b/agent_docs/ml-pipeline.md index 67c9e5f..3c65776 100644 --- a/agent_docs/ml-pipeline.md +++ b/agent_docs/ml-pipeline.md @@ -86,6 +86,14 @@ labels in `ml/real_data/labels/`. - Commands (from `ml/`): `python -m real_data.build fetch | sheets | convert | verify | report`; tests: `pytest tests`. - The test split hash is frozen: change the pilot or the labels and `convert` produces a new hash, which is a new eval set (record it, do not tune on it). +## 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). +`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). + ## Key Principle Dataset quality > annotation correctness > pipeline correctness > model architecture. Fix data before changing models. @@ -97,7 +105,7 @@ Fix data before changing models. | Detection | YOLOv8 (ultralytics), pretrained COCO weights | | Image processing | OpenCV | | Graph | NetworkX | -| Training | Google Colab T4 | +| Training | Kaggle GPUs (`ml/kaggle/train_kaggle.py`), local CPU for smoke runs (`ml/train.py`) | | Inference | Local / Azure | ## What We Are NOT Doing diff --git a/ml/kaggle/train_kaggle.py b/ml/kaggle/train_kaggle.py new file mode 100644 index 0000000..7d21180 --- /dev/null +++ b/ml/kaggle/train_kaggle.py @@ -0,0 +1,606 @@ +""" +Module: train_kaggle.py +Purpose: Single-file Kaggle entry point for the DigiSim detector training (twin of ml/train.py, kept + self-contained so it can be pasted into / uploaded as a Kaggle notebook script without the repo). + It installs ultralytics, finds the dataset under /kaggle/input, trains on every visible GPU + (DDP) or the CPU, then writes best.pt, best.onnx, metrics.json (and config.yaml) to + /kaggle/working/digisim_run. Run it as a script (`!python train_kaggle.py ...`), not via %run, + because ultralytics DDP re-launches the trainer in child processes. + +Usage (notebook cell, GPU T4 x2 / L4 x4 accelerator, internet on for the pip install and COCO weights): + !python train_kaggle.py --preset stage-a # auto-detects /kaggle/input/**/data.yaml + !python train_kaggle.py --preset stage-a --device 0,1,2,3 --epochs 100 + !python train_kaggle.py --preset stage-b --model /kaggle/input/stage-a/best.pt --real-train images/real + !python train_kaggle.py --preset stage-a --dry-run # print the plan, install/train nothing + +The dataset's data.yaml must come from `cd ml && uv run python class_schema.py data-yaml --path DIR` so class ids match +ml/classes.yaml. Kaggle input is read-only: the script rewrites the yaml into the output folder (absolute `path:`) and +ultralytics keeps its label cache in memory when it cannot write next to the labels. +Keep the PRESETS table in sync with ml/train.py (ml/tests/test_train_harness.py asserts it). +""" + +import argparse +import json +import os +import platform +import shutil +import subprocess +import sys +import time +from collections.abc import Iterable, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +KAGGLE_INPUT = Path("/kaggle/input") +KAGGLE_WORKING = Path("/kaggle/working") +IMAGE_SUFFIXES = frozenset({".jpg", ".jpeg", ".png", ".bmp", ".webp"}) +DATA_YAML_NAMES = ("data.yaml", "dataset.yaml") +F1_THRESHOLD = 0.95 +ACC_THRESHOLD = 0.95 +METRICS_SCHEMA_VERSION = 1 +ONNX_OPSET = 17 +SEED = 0 +REQUIREMENTS = ("ultralytics>=8.3", "onnx", "onnxslim", "onnxruntime", "pyyaml") + + +@dataclass(frozen=True) +class Preset: + """Default hyper-parameters of one training stage (mirror of ml/train.py).""" + + name: str + model: str | None + imgsz: int + epochs: int + batch_per_device: int + patience: int + lr0: float + lrf: float + warmup_epochs: float + close_mosaic: int + real_oversample: int + plots: bool + + +PRESETS: dict[str, Preset] = { + "smoke": Preset("smoke", "yolov8n.pt", 320, 2, 8, 2, 0.01, 0.01, 0.0, 0, 1, False), + "stage-a": Preset("stage-a", "yolov8s.pt", 960, 100, 16, 20, 0.01, 0.01, 3.0, 10, 1, True), + "stage-b": Preset("stage-b", None, 960, 40, 16, 15, 0.002, 0.1, 1.0, 5, 4, True), +} + + +def default_workers() -> int: + """ + Default dataloader worker count derived from the CPUs this process may use. + + Returns: + A value in [1, 8]. + """ + try: + cpus = len(os.sched_getaffinity(0)) + except AttributeError: + cpus = os.cpu_count() or 1 + return max(1, min(8, cpus)) + + +def detect_cuda_count() -> int: + """ + Count visible CUDA devices without requiring torch to be installed. + + Returns: + Number of CUDA devices, 0 when torch is missing or no GPU is visible. + """ + try: + import torch + except ImportError: + return 0 + return int(torch.cuda.device_count()) + + +def parse_device(spec: str, cuda_count: int | None = None) -> tuple[int, ...]: + """ + Parse a --device value into CUDA indices (pure string handling, so it works on a machine without a GPU). + + Args: + spec: 'cpu', 'auto' (all visible GPUs, else CPU), '0', or a comma list like '0,1,2,3'. + cuda_count: Visible GPU count used by 'auto'; detected via torch when None. + Returns: + Device indices; an empty tuple means the CPU. + Raises: + ValueError: If the spec is malformed, negative or lists a device twice. + """ + text = spec.strip().lower().replace(" ", "") + if text == "cpu": + return () + if text == "auto": + return tuple(range(detect_cuda_count() if cuda_count is None else cuda_count)) + try: + ids = tuple(int(p.removeprefix("cuda:")) for p in text.split(",") if p != "") + except ValueError as exc: + raise ValueError(f"Bad --device {spec!r}: use 'cpu', 'auto', '0' or '0,1,2,3'") from exc + if not ids or any(i < 0 for i in ids) or len(set(ids)) != len(ids): + raise ValueError(f"Bad --device {spec!r}: need unique non-negative device indices") + return ids + + +def device_spec(ids: Sequence[int]) -> str: + """ + Format device indices for ultralytics. + + Args: + ids: Device indices (empty for CPU). + Returns: + 'cpu' or '0,1,2,3'. + """ + return ",".join(str(i) for i in ids) if ids else "cpu" + + +def resolve_batch(requested: int | None, per_device: int, world_size: int) -> int: + """ + Resolve the total batch size (ultralytics splits it evenly across DDP processes). + + Args: + requested: Total batch from --batch, or None for per-device default x world size. + per_device: Preset batch per device. + world_size: Number of GPU processes (1 for CPU). + Returns: + The total batch size. + Raises: + ValueError: If the batch is not positive or not divisible by the GPU count. + """ + batch = per_device * world_size if requested is None else requested + if batch == -1 and world_size == 1: + return batch + if batch < 1: + raise ValueError(f"batch must be >= 1 (got {batch}); -1 auto-batch is single-device only") + if batch % world_size: + raise ValueError(f"batch {batch} must be a multiple of the GPU count {world_size} for DDP") + return batch + + +def find_data_yaml(root: Path = KAGGLE_INPUT, hint: str = "") -> Path: + """ + Locate the dataset yaml under the Kaggle input folder (searches up to 4 levels deep). + + Args: + root: Folder to search (default /kaggle/input). + hint: Optional substring that must appear in the yaml's path to disambiguate several datasets. + Returns: + The single matching data.yaml. + Raises: + FileNotFoundError: If none is found. + ValueError: If several match (pass --data or --dataset-hint). + """ + candidates: list[Path] = [] + if root.is_dir(): + for name in DATA_YAML_NAMES: + for depth in range(4): + candidates += root.glob("/".join(["*"] * depth + [name])) + found = sorted({p for p in candidates if hint in str(p)}) + if not found: + raise FileNotFoundError(f"No data.yaml under {root}" + (f" matching {hint!r}" if hint else "") + " - attach the dataset to the notebook or pass --data") + if len(found) > 1: + raise ValueError("Several datasets found, pass --data or --dataset-hint: " + ", ".join(str(p) for p in found)) + return found[0] + + +def read_yaml(path: Path) -> dict[str, Any]: + """ + Parse a YAML file into a mapping. + + Args: + path: YAML file. + Returns: + The parsed mapping. + Raises: + ValueError: If the file is not a mapping. + """ + import yaml + + cfg = yaml.safe_load(path.read_text()) + if not isinstance(cfg, dict): + raise ValueError(f"{path}: expected a YAML mapping") + return cfg + + +def list_images(entries: Iterable[Path]) -> list[Path]: + """ + Expand image files, image directories and .txt lists into a sorted, de-duplicated image list. + + Args: + entries: Image files, directories (recursive) or .txt lists (one path per line). + Returns: + Absolute image paths, sorted. + """ + found: set[Path] = set() + for entry in entries: + if entry.is_dir(): + found.update(p.resolve() for p in entry.rglob("*") if p.suffix.lower() in IMAGE_SUFFIXES) + elif entry.suffix == ".txt" and entry.is_file(): + for line in entry.read_text().splitlines(): + if line.strip(): + p = Path(line.strip()) + found.add((p if p.is_absolute() else entry.parent / p).resolve()) + elif entry.suffix.lower() in IMAGE_SUFFIXES and entry.is_file(): + found.add(entry.resolve()) + return sorted(found) + + +def split_images(cfg: dict[str, Any], root: Path, split: str) -> list[Path]: + """ + Images of one split of a dataset yaml (empty when the split is not declared). + + Args: + cfg: Parsed data.yaml. + root: Dataset root that the split entries are relative to. + split: 'train', 'val' or 'test'. + Returns: + Sorted absolute image paths. + """ + value = cfg.get(split) + if not value: + return [] + return list_images(root / str(item) for item in (value if isinstance(value, list) else [value])) + + +def prepare_data_yaml(data_yaml: Path, out_dir: Path, real_train: Sequence[Path], oversample: int) -> tuple[Path, dict[str, int]]: + """ + Write a data yaml that points at the (read-only) dataset by absolute path, optionally oversampling real images. + + Args: + data_yaml: The dataset yaml found under /kaggle/input. + out_dir: Writable folder for the rewritten yaml and train list. + real_train: Real training image folders/lists (relative paths resolve against the dataset folder). + oversample: Times each real image repeats per epoch (1 = off). + Returns: + (path of the yaml to train on, split image counts). + Raises: + ValueError: If the yaml lacks train/val/names, no real image is found, or real images leak into val/test. + """ + cfg = read_yaml(data_yaml) + if not {"train", "val", "names"} <= cfg.keys() or not cfg["names"]: + raise ValueError(f"{data_yaml}: expected a YOLO data.yaml with train, val and a non-empty names") + # The dataset travels between machines, so ignore any absolute `path:` written at generation time. + root = data_yaml.parent + counts = {split: len(split_images(cfg, root, split)) for split in ("train", "val", "test")} + out_cfg = {**cfg, "path": str(root.resolve())} + out_dir.mkdir(parents=True, exist_ok=True) + if real_train: + real = list_images(p if p.is_absolute() else root / p for p in real_train) + if not real: + raise ValueError(f"No images found under --real-train {[str(p) for p in real_train]}") + held_out = set(split_images(cfg, root, "val")) | set(split_images(cfg, root, "test")) + if held_out & set(real): + raise ValueError("Real training images overlap the val/test split (leakage)") + real_set = set(real) + lines = [str(p) for p in split_images(cfg, root, "train") if p not in real_set] + [str(p) for p in real for _ in range(oversample)] + (out_dir / "train_mixed.txt").write_text("\n".join(lines) + "\n") + out_cfg["train"] = str(out_dir / "train_mixed.txt") + counts["train"] = len(lines) + import yaml + + out_yaml = out_dir / "data.yaml" + out_yaml.write_text(yaml.safe_dump(out_cfg, sort_keys=False)) + return out_yaml, counts + + +def per_class_metrics(box: Any, names: dict[int, str], confusion: Any, instances: Any) -> dict[str, dict[str, float]]: + """ + Per-class precision/recall/F1/AP/accuracy from an ultralytics validation result (same as ml/train.py). + + Args: + box: The `metrics.box` object (duck-typed ultralytics result). + names: Class id to name map of the model. + confusion: The validator confusion matrix (matrix[pred, gt]) or None. + instances: Per-class ground-truth counts or None. + Returns: + Class name to metric dict; accuracy = confusion TP / all ground truth of the class. + """ + import numpy as np + + idx = np.atleast_1d(getattr(box, "ap_class_index", [])).astype(int) + columns = {key: np.atleast_1d(getattr(box, attr, np.zeros(len(idx)))) for key, attr in (("precision", "p"), ("recall", "r"), ("f1", "f1"), ("ap50", "ap50"), ("ap50_95", "ap"))} + counts = None if instances is None else np.atleast_1d(instances) + matrix = getattr(confusion, "matrix", None) + out: dict[str, dict[str, float]] = {} + for pos, cls_id in enumerate(idx): + entry = {key: float(col[pos]) for key, col in columns.items()} + if counts is not None and cls_id < len(counts): + entry["instances"] = float(counts[cls_id]) + if matrix is not None and cls_id < matrix.shape[1] and matrix[:, cls_id].sum() > 0: + entry["accuracy"] = float(matrix[cls_id, cls_id]) / float(matrix[:, cls_id].sum()) + out[names[int(cls_id)]] = entry + return out + + +def gate_verdict(per_class: dict[str, dict[str, float]]) -> dict[str, Any]: + """ + Apply the phase gate (F1 >= 0.95 and accuracy >= 0.95 per class). + + Args: + per_class: Output of per_class_metrics(). + Returns: + Thresholds, failing class names and the overall pass flag (False when nothing was evaluated). + """ + failing = [n for n, m in per_class.items() if m.get("f1", 0.0) < F1_THRESHOLD or m.get("accuracy", 0.0) < ACC_THRESHOLD] + return {"f1_threshold": F1_THRESHOLD, "accuracy_threshold": ACC_THRESHOLD, "failing_classes": failing, "passed": bool(per_class) and not failing} + + +def install_requirements(requirements: Sequence[str] = REQUIREMENTS) -> None: + """ + Pip-install the training dependencies (Kaggle already ships torch; this adds ultralytics and the ONNX toolchain). + + Args: + requirements: pip requirement specifiers. + Raises: + subprocess.CalledProcessError: If pip fails (typically the notebook's internet toggle is off). + """ + subprocess.run([sys.executable, "-m", "pip", "install", "-q", *requirements], check=True) + + +def environment_info() -> dict[str, Any]: + """ + Describe the software and hardware the run executed on. + + Returns: + Versions, CPU count and GPU names (None / empty when not importable). + """ + info: dict[str, Any] = {"python": platform.python_version(), "platform": platform.platform(), "cpu_count": os.cpu_count(), "torch": None, "ultralytics": None, "cuda_devices": []} + try: + import torch + + info["torch"] = torch.__version__ + info["cuda_devices"] = [torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())] + except ImportError: + pass + try: + import ultralytics + + info["ultralytics"] = ultralytics.__version__ + except ImportError: + pass + return info + + +def resolve_resume_checkpoint(target: Path) -> Path: + """ + Locate last.pt from a run directory, a train directory or the checkpoint itself. + + Args: + target: A run dir, its train/ subdir, or a last.pt path. + Returns: + Path to last.pt. + Raises: + FileNotFoundError: If no checkpoint is found. + """ + for candidate in (target, target / "weights" / "last.pt", target / "train" / "weights" / "last.pt", target / "last.pt"): + if candidate.is_file() and candidate.suffix == ".pt": + return candidate + raise FileNotFoundError(f"No last.pt checkpoint found for --resume {target}") + + +def build_plan(args: argparse.Namespace) -> dict[str, Any]: + """ + Resolve preset defaults and CLI overrides into one settings dict (no side effects beyond path discovery). + + Args: + args: Parsed CLI arguments. + Returns: + Settings: preset, model, device ids/spec, world size, batch, workers, epochs, imgsz, data yaml (or None plus a warning), run dir. + Raises: + ValueError: If the device, batch, stage-B model or oversample settings are invalid. + FileNotFoundError: If --resume points at nothing. + """ + ids = parse_device(args.device) + world = max(1, len(ids)) + resume = resolve_resume_checkpoint(args.resume) if args.resume else None + 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) + if model is None: + raise ValueError(f"preset {preset.name} fine-tunes earlier weights: pass --model /kaggle/input//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 + if oversample > 1 and not real_train: + raise ValueError("--real-oversample needs at least one --real-train folder") + warnings: list[str] = [] + data_yaml: Path | None = None + try: + data_yaml = args.data or (Path(saved["data_yaml"]) if saved.get("data_yaml") else find_data_yaml(args.input_root, args.dataset_hint)) + if not data_yaml.is_file(): + raise FileNotFoundError(f"{data_yaml} not found") + except (FileNotFoundError, ValueError) as exc: + warnings.append(f"dataset: {exc}") + data_yaml = None + return { + "preset": preset.name, + "model": model, + "resume": str(resume) if resume else None, + "device_ids": list(ids), + "device": device_spec(ids), + "world_size": world, + "ddp": world > 1, + "batch_total": resolve_batch(args.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), + "patience": args.patience if args.patience is not None else int(saved.get("patience") or preset.patience), + "lr0": args.lr0 if args.lr0 is not None else float(saved.get("lr0") or preset.lr0), + "lrf": preset.lrf, + "warmup_epochs": preset.warmup_epochs, + "close_mosaic": preset.close_mosaic, + "plots": preset.plots if args.plots is None else args.plots, + "seed": args.seed if args.seed is not None else int(saved.get("seed") or SEED), + "real_train": [str(p) for p in real_train], + "real_oversample": oversample, + "data_yaml": str(data_yaml) if data_yaml else None, + "out_dir": str(out_dir), + "warnings": warnings, + } + + +def run(plan: dict[str, Any], install: bool) -> Path: + """ + Execute the plan: install deps, train (DDP on every listed GPU), validate best.pt, export ONNX, write metrics.json. + + Args: + plan: Output of build_plan() with a resolvable data_yaml. + install: Whether to pip-install the requirements first. + Returns: + The output directory with best.pt, best.onnx, metrics.json and config.yaml. + Raises: + FileNotFoundError: If no dataset yaml was found. + """ + if not plan["data_yaml"]: + raise FileNotFoundError("; ".join(plan["warnings"]) or "no dataset") + if install: + install_requirements() + import yaml + from ultralytics import YOLO + + out = Path(plan["out_dir"]) + out.mkdir(parents=True, exist_ok=True) + data_yaml, counts = prepare_data_yaml(Path(plan["data_yaml"]), out, [Path(p) for p in plan["real_train"]], plan["real_oversample"]) + data_cfg = read_yaml(data_yaml) + (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 + if plan["resume"]: + model.train(resume=True, device=plan["device"], batch=plan["batch_total"], imgsz=plan["imgsz"], workers=plan["workers"]) + else: + model.train( + data=str(data_yaml), + epochs=plan["epochs"], + imgsz=plan["imgsz"], + batch=plan["batch_total"], + device=plan["device"], + workers=plan["workers"], + patience=plan["patience"], + seed=plan["seed"], + lr0=plan["lr0"], + lrf=plan["lrf"], + warmup_epochs=plan["warmup_epochs"], + close_mosaic=plan["close_mosaic"], + plots=plan["plots"], + project=str(out), + name="train", + exist_ok=True, + ) + best = Path(model.trainer.best) if Path(model.trainer.best).is_file() else Path(model.trainer.last) + + split = "test" if data_cfg.get("test") else "val" + eval_device = "cpu" if not plan["device_ids"] else str(plan["device_ids"][0]) # single-process validation even after DDP + best_model = YOLO(str(best)) + val = best_model.val(data=str(data_yaml), split=split, imgsz=plan["imgsz"], batch=16, device=eval_device, workers=0, plots=True, project=str(out), name="val", exist_ok=True) + per_class = per_class_metrics(val.box, best_model.names, getattr(val, "confusion_matrix", None), getattr(val, "nt_per_class", None)) + onnx_src = Path(best_model.export(format="onnx", imgsz=plan["imgsz"], opset=ONNX_OPSET, simplify=True, dynamic=False, device="cpu")) + shutil.copy2(best, out / "best.pt") + shutil.copy2(onnx_src, out / "best.onnx") + + summary = { + "schema_version": METRICS_SCHEMA_VERSION, + "run_name": out.name, + "preset": plan["preset"], + "map50": float(val.box.map50), + "map50_95": float(val.box.map), + "mean_precision": float(val.box.mp), + "mean_recall": float(val.box.mr), + "eval_split": split, + "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"]}, + "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), + "weights": str(out / "best.pt"), + "onnx": str(out / "best.onnx"), + } + (out / "metrics.json").write_text(json.dumps(summary, indent=2)) + print(f"\nWrote {out}/best.pt, best.onnx, metrics.json") + return out + + +def build_parser() -> argparse.ArgumentParser: + """ + Build the CLI parser (all tunables default to None so presets can fill them in). + + Returns: + The configured parser. + """ + p = argparse.ArgumentParser(description="Kaggle training entry point for the DigiSim detector") + p.add_argument( + "--preset", choices=sorted(PRESETS), default=None, help="default stage-a (or the resumed run's preset). stage-a: synthetic pretrain | stage-b: mixed fine-tune | smoke: 2-epoch check" + ) + p.add_argument("--data", type=Path, default=None, help="data.yaml (default: discovered under --input-root)") + p.add_argument("--input-root", type=Path, default=KAGGLE_INPUT) + p.add_argument("--dataset-hint", default="", help="substring that disambiguates several attached datasets") + p.add_argument("--model", default=None, help="pretrained .pt to start from (stage-b: the stage-A best.pt)") + p.add_argument("--device", default="auto", help="auto (all visible GPUs, else CPU) | cpu | 0 | 0,1,2,3") + p.add_argument("--epochs", type=int, default=None) + p.add_argument("--imgsz", type=int, default=None) + p.add_argument("--batch", type=int, default=None, help="TOTAL batch across GPUs (default: per-device preset x GPUs)") + p.add_argument("--workers", type=int, default=None) + p.add_argument("--patience", type=int, default=None) + p.add_argument("--lr0", type=float, default=None) + p.add_argument("--seed", type=int, default=None, help=f"default {SEED} (or the resumed run's seed)") + p.add_argument("--plots", action=argparse.BooleanOptionalAction, default=None) + p.add_argument("--real-train", action="append", default=[], help="real training image folder/list, relative to the dataset folder (repeatable)") + p.add_argument("--real-oversample", type=int, default=None, help="times each real image repeats per epoch (stage-b default 4)") + p.add_argument("--resume", type=Path, default=None, help="run dir, train dir or last.pt of an interrupted run; reuses its saved config.yaml and folder") + p.add_argument("--out", type=Path, default=KAGGLE_WORKING / "digisim_run") + p.add_argument("--skip-install", action="store_true", help="do not pip install ultralytics/onnx") + p.add_argument("--dry-run", action="store_true", help="print the resolved plan as JSON and exit; installs and trains nothing") + return p + + +def strip_kernel_args(argv: Sequence[str]) -> list[str]: + """ + Drop the `-f ` pair a Jupyter kernel injects into sys.argv; every other argument is kept. + + Args: + argv: Raw argument list. + Returns: + The list without `-f` and its value. + """ + kept: list[str] = [] + skip = False + for arg in argv: + if skip: + skip = False + elif arg == "-f": + skip = True + elif not arg.startswith("-f="): + kept.append(arg) + return kept + + +def main(argv: Sequence[str] | None = None) -> int: + """ + CLI entry point (rejects unknown arguments, except the Jupyter kernel's `-f connection.json`). + + Args: + argv: Argument list (defaults to sys.argv[1:]). + Returns: + Process exit code (0 on success, 2 on invalid configuration or missing dataset). + """ + args = build_parser().parse_args(strip_kernel_args(sys.argv[1:] if argv is None else argv)) + try: + plan = build_plan(args) + if args.dry_run: + print(json.dumps(plan, indent=2)) + return 0 + run(plan, install=not args.skip_install) + except (ValueError, FileNotFoundError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ml/make_smoke_dataset.py b/ml/make_smoke_dataset.py new file mode 100644 index 0000000..ce0c6d4 --- /dev/null +++ b/ml/make_smoke_dataset.py @@ -0,0 +1,134 @@ +""" +Module: make_smoke_dataset.py +Purpose: Generates a tiny throwaway YOLO dataset (procedural glyphs with exact boxes, class names from + ml/classes.yaml) for exercising the training harness end to end on CPU or in CI. It is NOT + training data for the real detector - the glyphs are crude and carry no circuit meaning; real + data comes from the synthetic generator and the real-data ingestion tasks. Output stays out of git. + +Usage: + cd ml && uv run python make_smoke_dataset.py --out /tmp/digisim_smoke --count 200 +""" + +import argparse +import sys +from collections.abc import Sequence +from pathlib import Path + +import cv2 +import numpy as np + +from class_schema import load_schema, render_data_yaml + +IMAGE_SIZE = 320 +SPLIT_FRACTIONS: tuple[tuple[str, float], ...] = (("train", 0.7), ("valid", 0.15), ("test", 0.15)) + + +def draw_glyph(canvas: np.ndarray, class_id: int, center: tuple[int, int], size: int) -> tuple[int, int, int, int]: + """ + Draw one crude class-specific glyph (polygon with class-dependent corner count, plus a stripe pattern). + + Args: + canvas: BGR image to draw on (modified in place). + class_id: YOLO class id; selects the glyph shape. + center: Glyph centre in pixels. + size: Glyph edge length in pixels. + Returns: + Pixel box (x1, y1, x2, y2) tightly enclosing the glyph, clipped to the canvas. + """ + cx, cy = center + half = size // 2 + sides = 3 + class_id % 6 + angles = np.linspace(0, 2 * np.pi, sides, endpoint=False) + (class_id % 4) * np.pi / 8 + pts = np.stack([cx + half * np.cos(angles), cy + half * np.sin(angles)], axis=1).astype(np.int32) + shade = 30 + (class_id * 37) % 140 + cv2.polylines(canvas, [pts], True, (shade, shade, shade), 2) + for k in range(class_id % 4): + y = cy - half // 2 + k * (half // 2) + cv2.line(canvas, (cx - half // 2, y), (cx + half // 2, y), (shade, shade, shade), 1) + h, w = canvas.shape[:2] + x1, y1 = np.clip(pts.min(axis=0) - 1, 0, [w - 1, h - 1]) + x2, y2 = np.clip(pts.max(axis=0) + 1, 0, [w - 1, h - 1]) + return int(x1), int(y1), int(x2), int(y2) + + +def make_image(rng: np.random.Generator, nc: int) -> tuple[np.ndarray, list[str]]: + """ + Compose one image with 2-5 non-overlapping glyphs and their YOLO label lines. + + Args: + rng: Seeded random generator. + nc: Number of classes to draw from. + Returns: + (BGR image, label lines ' ' normalised). + """ + canvas = np.full((IMAGE_SIZE, IMAGE_SIZE, 3), 255, dtype=np.uint8) + labels: list[str] = [] + taken: list[tuple[int, int, int, int]] = [] + for _ in range(int(rng.integers(2, 6))): + size = int(rng.integers(36, 72)) + cx = int(rng.integers(size, IMAGE_SIZE - size)) + cy = int(rng.integers(size, IMAGE_SIZE - size)) + probe = (cx - size, cy - size, cx + size, cy + size) + if any(probe[0] < t[2] and probe[2] > t[0] and probe[1] < t[3] and probe[3] > t[1] for t in taken): + continue + cls = int(rng.integers(0, nc)) + x1, y1, x2, y2 = draw_glyph(canvas, cls, (cx, cy), size) + taken.append(probe) + labels.append(f"{cls} {(x1 + x2) / 2 / IMAGE_SIZE:.6f} {(y1 + y2) / 2 / IMAGE_SIZE:.6f} {(x2 - x1) / IMAGE_SIZE:.6f} {(y2 - y1) / IMAGE_SIZE:.6f}") + noise = rng.integers(-6, 7, canvas.shape, dtype=np.int16) + return np.clip(canvas.astype(np.int16) + noise, 0, 255).astype(np.uint8), labels + + +def generate(out: Path, count: int, seed: int) -> Path: + """ + Write a YOLO dataset (images/, labels/, data.yaml) with train/valid/test splits. + + Args: + out: Output dataset root (created). + count: Total number of images. + seed: RNG seed (same seed gives identical files). + Returns: + Path to the generated data.yaml. + Raises: + ValueError: If count is too small to fill every split. + """ + if count < len(SPLIT_FRACTIONS) * 2: + raise ValueError("count must be at least 6 so every split has images") + schema = load_schema() + nc = len(schema.classes_up_to("A")) + rng = np.random.default_rng(seed) + n_valid = max(1, round(count * SPLIT_FRACTIONS[1][1])) + n_test = max(1, round(count * SPLIT_FRACTIONS[2][1])) + sizes = {"train": count - n_valid - n_test, "valid": n_valid, "test": n_test} + for split, n in sizes.items(): + (out / "images" / split).mkdir(parents=True, exist_ok=True) + (out / "labels" / split).mkdir(parents=True, exist_ok=True) + for i in range(n): + image, labels = make_image(rng, nc) + cv2.imwrite(str(out / "images" / split / f"smoke_{split}_{i:04d}.jpg"), image) + (out / "labels" / split / f"smoke_{split}_{i:04d}.txt").write_text("\n".join(labels) + ("\n" if labels else "")) + data_yaml = out / "data.yaml" + data_yaml.write_text(render_data_yaml(schema, out, "A")) + return data_yaml + + +def main(argv: Sequence[str] | None = None) -> int: + """ + CLI entry point. + + Args: + argv: Argument list (defaults to sys.argv[1:]). + Returns: + Process exit code. + """ + parser = argparse.ArgumentParser(description="Generate a tiny throwaway YOLO dataset for harness smoke tests") + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--count", type=int, default=200) + parser.add_argument("--seed", type=int, default=0) + args = parser.parse_args(argv) + print(generate(args.out, args.count, args.seed)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ml/pyproject.toml b/ml/pyproject.toml index 7f1eb0d..d9ec4a9 100644 --- a/ml/pyproject.toml +++ b/ml/pyproject.toml @@ -10,6 +10,9 @@ dependencies = [ "pillow>=10.1", "scipy>=1.11", "huggingface_hub>=0.24", + "onnx>=1.16", + "onnxslim>=0.1.34", + "onnxruntime>=1.18", ] [dependency-groups] @@ -28,3 +31,4 @@ select = ["E", "F", "I"] [tool.pytest.ini_options] pythonpath = ["."] testpaths = ["tests"] +markers = ["smoke: end-to-end CPU training run (needs network for pretrained weights; enable with DIGISIM_ML_SMOKE=1)"] diff --git a/ml/tests/test_train_harness.py b/ml/tests/test_train_harness.py new file mode 100644 index 0000000..4474643 --- /dev/null +++ b/ml/tests/test_train_harness.py @@ -0,0 +1,477 @@ +""" +Module: test_train_harness.py +Purpose: Tests for the training harness (ml/train.py) and its single-file Kaggle twin + (ml/kaggle/train_kaggle.py): device parsing for cpu/0/0,1,2,3, dry-run plans, batch and + workers defaults, preset parity between the two scripts, real-image oversampling, + resume lookup, metrics assembly, and an opt-in end-to-end CPU smoke run + (DIGISIM_ML_SMOKE=1) that must produce metrics.json and an ONNX file. +""" + +import importlib.util +import json +import os +import subprocess +import sys +from pathlib import Path +from types import ModuleType, SimpleNamespace + +import numpy as np +import pytest +import yaml + +import make_smoke_dataset +import train + +ML_DIR = Path(__file__).resolve().parents[1] +KAGGLE_PATH = ML_DIR / "kaggle" / "train_kaggle.py" + + +def load_kaggle() -> ModuleType: + """ + Import ml/kaggle/train_kaggle.py by path (it is deliberately not a package module). + + Returns: + The loaded module. + """ + spec = importlib.util.spec_from_file_location("train_kaggle", KAGGLE_PATH) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules["train_kaggle"] = module + spec.loader.exec_module(module) + return module + + +train_kaggle = load_kaggle() + + +@pytest.fixture(scope="module") +def smoke_data(tmp_path_factory: pytest.TempPathFactory) -> Path: + """ + A 24-image throwaway dataset shared by the module. + + Args: + tmp_path_factory: pytest temp factory. + Returns: + Path to its data.yaml. + """ + return make_smoke_dataset.generate(tmp_path_factory.mktemp("smoke"), 24, seed=3) + + +def parse(argv: list[str]) -> train.TrainConfig: + """ + Run the real CLI parser and resolver on an argv list. + + Args: + argv: Command-line arguments. + Returns: + The resolved config. + """ + return train.resolve_config(train.build_parser().parse_args(argv)) + + +@pytest.mark.parametrize( + ("spec", "ids", "world", "text"), + [("cpu", (), 1, "cpu"), ("0", (0,), 1, "0"), ("0,1,2,3", (0, 1, 2, 3), 4, "0,1,2,3"), (" 0, 1 ", (0, 1), 2, "0,1"), ("cuda:1", (1,), 1, "1")], +) +def test_parse_device(spec: str, ids: tuple[int, ...], world: int, text: str) -> None: + """ + parse_device accepts cpu / single GPU / GPU lists without any GPU present and both scripts agree. + + Args: + spec: Device string. + ids: Expected indices. + world: Expected DDP world size. + text: Expected ultralytics device string. + """ + plan = train.parse_device(spec) + assert plan.ids == ids and plan.world_size == world and plan.spec == text + assert train_kaggle.parse_device(spec) == ids and train_kaggle.device_spec(ids) == text + + +@pytest.mark.parametrize("bad", ["", "gpu", "0,0", "-1", "0,,x"]) +def test_parse_device_rejects_garbage(bad: str) -> None: + """ + Malformed device strings fail loudly in both scripts. + + Args: + bad: Invalid device string. + """ + with pytest.raises(ValueError): + train.parse_device(bad) + with pytest.raises(ValueError): + train_kaggle.parse_device(bad) + + +def test_auto_device_uses_visible_gpu_count() -> None: + """auto resolves to every visible GPU, or the CPU when there is none.""" + assert train.parse_device("auto", cuda_count=0).is_cpu + assert train.parse_device("auto", cuda_count=4).ids == (0, 1, 2, 3) + assert train_kaggle.parse_device("auto", cuda_count=2) == (0, 1) + + +def test_batch_defaults_scale_with_gpus_and_must_divide() -> None: + """The default batch is per-device x GPUs; an explicit batch must split evenly across DDP processes.""" + assert parse(["--preset", "stage-a", "--device", "0,1,2,3"]).batch == 64 + assert parse(["--preset", "stage-a", "--device", "cpu"]).batch == 16 + with pytest.raises(ValueError, match="multiple"): + parse(["--device", "0,1,2", "--batch", "16"]) + with pytest.raises(ValueError, match="batch must be"): + parse(["--device", "0,1", "--batch", "-1"]) + assert parse(["--device", "0", "--batch", "-1"]).batch == -1 + + +def test_workers_default_follows_cpu_count(monkeypatch: pytest.MonkeyPatch) -> None: + """--workers defaults from the CPUs this process may use (capped at 8), never a constant.""" + monkeypatch.setattr(os, "sched_getaffinity", lambda _pid: set(range(3)), raising=False) + assert train.default_workers() == 3 and train_kaggle.default_workers() == 3 + monkeypatch.setattr(os, "sched_getaffinity", lambda _pid: set(range(64)), raising=False) + assert train.default_workers() == 8 + assert parse(["--workers", "2"]).workers == 2 + + +class FakeYOLO: + """Stand-in for ultralytics.YOLO that records every train/val/export call and writes the artifacts they would.""" + + calls: list[tuple[str, dict[str, object]]] = [] + root: Path = Path() + + def __init__(self, weights: str) -> None: + """ + Remember the weights and expose the attributes the harness reads. + + Args: + weights: Checkpoint path or name the harness asked for. + """ + self.weights = weights + self.names = {0: "NMOS"} + self.trainer = SimpleNamespace(best=str(self.root / "best.pt"), last=str(self.root / "last.pt"), save_dir=str(self.root)) + + def train(self, **kwargs: object) -> None: + """ + Record a training call. + + Args: + **kwargs: Arguments the harness passed to ultralytics. + """ + type(self).calls.append(("train", kwargs)) + + def val(self, **kwargs: object) -> SimpleNamespace: + """ + Record a validation call and return an empty-but-valid metrics object. + + Args: + **kwargs: Arguments the harness passed to ultralytics. + Returns: + A result with the attributes the harness reads. + """ + type(self).calls.append(("val", kwargs)) + box = SimpleNamespace(map50=0.5, map=0.4, mp=0.6, mr=0.7, ap_class_index=np.array([], dtype=int)) + return SimpleNamespace(box=box, confusion_matrix=None, nt_per_class=None) + + def export(self, **kwargs: object) -> str: + """ + Record an export call and write a placeholder ONNX file. + + Args: + **kwargs: Arguments the harness passed to ultralytics. + Returns: + Path of the placeholder file. + """ + type(self).calls.append(("export", kwargs)) + onnx = self.root / "model.onnx" + onnx.write_bytes(b"onnx") + return str(onnx) + + +@pytest.fixture +def fake_yolo(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> type[FakeYOLO]: + """ + Replace the ultralytics package with FakeYOLO so train()/run() execute for real without training. + + Args: + monkeypatch: pytest monkeypatch. + tmp_path: Per-test temp dir that holds the fake checkpoints. + Returns: + The FakeYOLO class (its `calls` list is fresh for each test). + """ + root = tmp_path / "fake_ultralytics" + root.mkdir() + for name in ("best.pt", "last.pt"): + (root / name).write_bytes(b"pt") + FakeYOLO.calls = [] + FakeYOLO.root = root + module = ModuleType("ultralytics") + module.YOLO = FakeYOLO # type: ignore[attr-defined] + module.__version__ = "0.0-test" # type: ignore[attr-defined] + monkeypatch.setitem(sys.modules, "ultralytics", module) + return FakeYOLO + + +def kinds(fake: type[FakeYOLO], kind: str) -> list[dict[str, object]]: + """ + Arguments of every recorded call of one kind. + + Args: + fake: The FakeYOLO class. + kind: 'train', 'val' or 'export'. + Returns: + The keyword-argument dicts, in call order. + """ + return [kw for k, kw in fake.calls if k == kind] + + +@pytest.mark.parametrize(("device", "val_device"), [("cpu", "cpu"), ("0", "0"), ("0,1,2,3", "0")]) +def test_device_reaches_ultralytics_and_export_stays_on_cpu(device: str, val_device: str, fake_yolo: type[FakeYOLO], smoke_data: Path, tmp_path: Path) -> None: + """Both scripts hand --device to training, validate single-process on the first GPU, and always export on the CPU.""" + cfg = parse(["--preset", "smoke", "--data", str(smoke_data), "--device", device, "--project", str(tmp_path / "runs"), "--name", "a"]) + run_dir = train.train(cfg) + plan = train_kaggle.build_plan(train_kaggle.build_parser().parse_args(["--preset", "smoke", "--data", str(smoke_data), "--device", device, "--out", str(tmp_path / "kaggle")])) + kaggle_dir = train_kaggle.run(plan, install=False) + for out in (run_dir, kaggle_dir): + assert (out / "metrics.json").is_file() and (out / "best.onnx").is_file() + trains, vals, exports = kinds(fake_yolo, "train"), kinds(fake_yolo, "val"), kinds(fake_yolo, "export") + assert [kw["device"] for kw in trains] == [device, device] + assert [kw["device"] for kw in vals] == [val_device, val_device] + assert [kw["device"] for kw in exports] == ["cpu", "cpu"] and all(kw["format"] == "onnx" for kw in exports) + + +def write_resumable_stage_b_run(run_dir: Path, real_dir: Path, data: Path) -> None: + """ + Lay out an interrupted stage-B run: a last.pt checkpoint plus the config.yaml both scripts write. + + Args: + run_dir: The run folder to create. + real_dir: The real-image folder that was oversampled. + data: The dataset yaml the run trained on. + """ + last = run_dir / "train" / "weights" / "last.pt" + last.parent.mkdir(parents=True) + last.write_bytes(b"pt") + saved = {"preset": "stage-b", "data": str(data), "data_yaml": str(data), "imgsz": 320, "epochs": 9, "patience": 7, "lr0": 0.003, "seed": 5, "real_train": [str(real_dir)], "real_oversample": 4} + (run_dir / "config.yaml").write_text(yaml.safe_dump(saved)) + + +@pytest.fixture +def real_images(tmp_path: Path) -> Path: + """ + Three throwaway real-image files outside the dataset. + + Args: + tmp_path: Per-test temp dir. + Returns: + The folder holding them. + """ + real_dir = tmp_path / "real" + real_dir.mkdir() + for i in range(3): + (real_dir / f"real_{i}.jpg").write_bytes(b"x") + return real_dir + + +def test_resume_keeps_real_oversampling(fake_yolo: type[FakeYOLO], smoke_data: Path, real_images: Path, tmp_path: Path) -> None: + """Resuming a stage-B run restores real_train, oversample, patience, lr0 and seed instead of silently dropping the mix.""" + run_dir = tmp_path / "runs" / "b" + write_resumable_stage_b_run(run_dir, real_images, smoke_data) + cfg = parse(["--resume", str(run_dir), "--device", "cpu"]) + assert cfg.real_train == (real_images,) and cfg.real_oversample == 4 + assert (cfg.patience, cfg.lr0, cfg.seed) == (7, 0.003, 5) + overridden = parse(["--resume", str(run_dir), "--device", "cpu", "--real-train", str(tmp_path), "--real-oversample", "2", "--seed", "0"]) + assert overridden.real_train == (tmp_path,) and overridden.real_oversample == 2 and overridden.seed == 0 + train.train(cfg) + assert kinds(fake_yolo, "train")[0]["resume"] is True + lines = (run_dir / "train_mixed.txt").read_text().split() + assert lines.count(str((real_images / "real_0.jpg").resolve())) == 4 + saved = yaml.safe_load((run_dir / "config.yaml").read_text()) + assert saved["real_train"] == [str(real_images)] and saved["real_oversample"] == 4 + assert json.loads((run_dir / "metrics.json").read_text())["dataset"]["real_oversample"] == 4 + + +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" + write_resumable_stage_b_run(out, real_images, smoke_data) + plan = train_kaggle.build_plan(train_kaggle.build_parser().parse_args(["--resume", str(out), "--device", "cpu"])) + assert plan["real_train"] == [str(real_images)] and plan["real_oversample"] == 4 + assert (plan["epochs"], plan["patience"], plan["lr0"], plan["seed"]) == (9, 7, 0.003, 5) + train_kaggle.run(plan, install=False) + assert kinds(fake_yolo, "train")[0]["resume"] is True + assert train_kaggle.read_yaml(out / "data.yaml")["train"] == str(out / "train_mixed.txt") + assert (out / "train_mixed.txt").read_text().split().count(str((real_images / "real_0.jpg").resolve())) == 4 + saved = yaml.safe_load((out / "config.yaml").read_text()) + assert saved["real_oversample"] == 4 and saved["real_train"] == [str(real_images)] + assert json.loads((out / "metrics.json").read_text())["dataset"]["real_oversample"] == 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"] + assert train_kaggle.main(["--data", str(smoke_data), "--device", "cpu", "-f", "/tmp/kernel.json", "--dry-run"]) == 0 + assert json.loads(capsys.readouterr().out)["device"] == "cpu" + for typo in ("--real_train", "--dataset_hint", "--bogus"): + with pytest.raises(SystemExit) as exc: + train_kaggle.main(["--dry-run", typo, "x"]) + assert exc.value.code == 2 + + +def test_presets_match_between_train_and_kaggle() -> None: + """The Kaggle script duplicates the preset table; every shared hyper-parameter must stay identical.""" + assert train.PRESETS.keys() == train_kaggle.PRESETS.keys() + for name, preset in train.PRESETS.items(): + twin = train_kaggle.PRESETS[name] + for field in ("model", "imgsz", "epochs", "batch_per_device", "patience", "lr0", "lrf", "warmup_epochs", "close_mosaic", "real_oversample", "plots"): + assert getattr(preset, field) == getattr(twin, field), f"{name}.{field} differs" + assert (train.F1_THRESHOLD, train.ACC_THRESHOLD, train.ONNX_OPSET) == (train_kaggle.F1_THRESHOLD, train_kaggle.ACC_THRESHOLD, train_kaggle.ONNX_OPSET) + + +def test_stage_b_requires_stage_a_weights() -> None: + """Stage B fine-tunes earlier weights, so it refuses to guess a base model.""" + with pytest.raises(ValueError, match="--model"): + parse(["--preset", "stage-b"]) + cfg = parse(["--preset", "stage-b", "--model", "a.pt", "--real-train", "/x"]) + assert cfg.model == "a.pt" and cfg.real_oversample == 4 and cfg.lr0 == 0.002 + with pytest.raises(ValueError, match="--real-train"): + parse(["--preset", "stage-a", "--real-oversample", "3"]) + + +@pytest.mark.parametrize("device", ["cpu", "0", "0,1,2,3"]) +def test_dry_run_runs_unchanged_for_any_device(device: str, smoke_data: Path, capsys: pytest.CaptureFixture[str]) -> None: + """The same command succeeds for cpu, 0 and 0,1,2,3 in --dry-run (no GPU, no torch, no training).""" + code = train.main(["--preset", "stage-a", "--data", str(smoke_data), "--device", device, "--dry-run"]) + plan = json.loads(capsys.readouterr().out) + assert code == 0 + assert plan["device"]["spec"] == device + assert plan["device"]["ddp"] == (device == "0,1,2,3") + assert plan["dataset"]["classes"] == 14 and plan["dataset"]["tier"] == "A" and plan["dataset"]["eval_split"] == "test" + assert plan["batch_total"] % plan["device"]["world_size"] == 0 + assert plan["workers"] >= 1 + + +def test_kaggle_dry_run_for_any_device(smoke_data: Path, capsys: pytest.CaptureFixture[str]) -> None: + """The Kaggle script dry-runs on a laptop for every device layout and tolerates a missing /kaggle/input.""" + for device in ("cpu", "0", "0,1,2,3"): + assert train_kaggle.main(["--preset", "stage-a", "--device", device, "--data", str(smoke_data), "--dry-run"]) == 0 + plan = json.loads(capsys.readouterr().out) + assert plan["device"] == device and plan["batch_total"] == 16 * max(1, len(plan["device_ids"])) + assert train_kaggle.main(["--dry-run", "--input-root", str(smoke_data.parent / "nowhere")]) == 0 + assert "No data.yaml" in json.loads(capsys.readouterr().out)["warnings"][0] + assert train_kaggle.main(["--device", "0,1,2", "--batch", "16", "--dry-run"]) == 2 + + +def test_dry_run_flags_class_drift(tmp_path: Path, smoke_data: Path, capsys: pytest.CaptureFixture[str]) -> None: + """A dataset whose names drift from classes.yaml is reported (dry-run) and refused (strict check).""" + text = smoke_data.read_text().replace("NMOS", "NFET") + drifted = tmp_path / "data.yaml" + drifted.write_text(text) + assert train.main(["--data", str(drifted), "--device", "cpu", "--dry-run"]) == 0 + assert any("classes.yaml" in w for w in json.loads(capsys.readouterr().out)["warnings"]) + with pytest.raises(ValueError, match="classes.yaml"): + train.check_class_vocabulary(train.dataset_names(train.load_data_yaml(drifted))) + + +def test_build_mixed_dataset_oversamples_real_and_blocks_leakage(tmp_path: Path, smoke_data: Path) -> None: + """Stage-B: each real image appears `factor` times, synthetic ones once, and val/test images are refused.""" + root = smoke_data.parent + real_dir = tmp_path / "real" / "images" / "train" + real_dir.mkdir(parents=True) + for i in range(3): + (real_dir / f"real_{i}.jpg").write_bytes(b"x") + out_yaml = train.build_mixed_dataset(smoke_data, [real_dir], 4, tmp_path / "out") + lines = (tmp_path / "out" / "train_mixed.txt").read_text().split() + base = train.split_images(train.load_data_yaml(smoke_data), smoke_data, "train") + assert len(lines) == len(base) + 3 * 4 + assert lines.count(str((real_dir / "real_0.jpg").resolve())) == 4 + derived = train.load_data_yaml(out_yaml) + assert derived["train"].endswith("train_mixed.txt") and derived["val"] == "images/valid" and Path(derived["path"]) == root.resolve() + with pytest.raises(ValueError, match="val/test"): + train.build_mixed_dataset(smoke_data, [root / "images" / "valid"], 2, tmp_path / "leak") + with pytest.raises(ValueError, match=">= 1"): + train.build_mixed_dataset(smoke_data, [real_dir], 0, tmp_path / "zero") + + +def test_kaggle_prepare_data_yaml_rewrites_path_and_oversamples(tmp_path: Path, smoke_data: Path) -> None: + """The Kaggle script re-roots the yaml at the dataset folder (ignoring a stale absolute path) and oversamples real images.""" + stale = smoke_data.read_text().replace(str(smoke_data.parent.resolve()), "/somewhere/else") + moved = tmp_path / "input" / "ds" + moved.mkdir(parents=True) + (moved / "images").symlink_to(smoke_data.parent / "images") + (moved / "labels").symlink_to(smoke_data.parent / "labels") + (moved / "data.yaml").write_text(stale) + assert train_kaggle.find_data_yaml(tmp_path / "input") == moved / "data.yaml" + with pytest.raises(FileNotFoundError): + train_kaggle.find_data_yaml(tmp_path / "input", hint="nomatch") + out_yaml, counts = train_kaggle.prepare_data_yaml(moved / "data.yaml", tmp_path / "work", [], 1) + assert train_kaggle.read_yaml(out_yaml)["path"] == str(moved.resolve()) and counts["train"] == 16 and counts["test"] == 4 + out_yaml, counts = train_kaggle.prepare_data_yaml(moved / "data.yaml", tmp_path / "work2", [Path("images/train")], 3) + assert counts["train"] == 16 * 3 + with pytest.raises(ValueError, match="leakage"): + train_kaggle.prepare_data_yaml(moved / "data.yaml", tmp_path / "work3", [Path("images/valid")], 2) + + +def test_resume_checkpoint_lookup(tmp_path: Path) -> None: + """--resume accepts a run dir, the train dir or last.pt itself and rejects anything without a checkpoint.""" + last = tmp_path / "run_x" / "train" / "weights" / "last.pt" + last.parent.mkdir(parents=True) + last.write_bytes(b"pt") + for target in (tmp_path / "run_x", tmp_path / "run_x" / "train", last): + assert train.resolve_resume_checkpoint(target) == last + assert train_kaggle.resolve_resume_checkpoint(target) == last + cfg = parse(["--resume", str(tmp_path / "run_x"), "--data", "d.yaml"]) + assert cfg.resume == last and cfg.model == str(last) and cfg.name == "run_x" and cfg.project == tmp_path + assert cfg.preset == "stage-a" and cfg.imgsz == 960 # no saved config.yaml: preset defaults + (tmp_path / "run_x" / "config.yaml").write_text("preset: smoke\nimgsz: 320\ndata: /d/data.yaml\nepochs: 4\n") + cfg = parse(["--resume", str(tmp_path / "run_x")]) + assert (cfg.preset, cfg.imgsz, cfg.epochs, cfg.data, cfg.project) == ("smoke", 320, 4, Path("/d/data.yaml"), tmp_path) + assert parse(["--resume", str(tmp_path / "run_x"), "--imgsz", "416"]).imgsz == 416 + saved = train_kaggle.build_plan(train_kaggle.build_parser().parse_args(["--resume", str(tmp_path / "run_x"), "--data", "d.yaml"])) + assert saved["preset"] == "smoke" and saved["imgsz"] == 320 and saved["out_dir"] == str(tmp_path / "run_x") + with pytest.raises(FileNotFoundError): + train.resolve_resume_checkpoint(tmp_path / "missing") + + +def test_metrics_assembly_and_gate() -> None: + """per_class_metrics derives accuracy from the confusion matrix like evaluate.py, and the gate lists failing classes.""" + box = SimpleNamespace(ap_class_index=np.array([0, 2]), p=np.array([0.9, 1.0]), r=np.array([0.8, 1.0]), f1=np.array([0.85, 0.99]), ap50=np.array([0.9, 0.99]), ap=np.array([0.7, 0.9])) + matrix = np.zeros((4, 4)) + matrix[0, 0], matrix[1, 0], matrix[2, 2] = 8, 2, 5 + names = {0: "NMOS", 1: "PMOS", 2: "VDD", 3: "GND"} + for module in (train, train_kaggle): + got = module.per_class_metrics(box, names, SimpleNamespace(matrix=matrix), np.array([10, 0, 5, 0])) + assert set(got) == {"NMOS", "VDD"} + assert got["NMOS"]["accuracy"] == pytest.approx(0.8) and got["NMOS"]["instances"] == 10 and got["VDD"]["accuracy"] == pytest.approx(1.0) + gate = module.gate_verdict(got) + assert gate["failing_classes"] == ["NMOS"] and gate["passed"] is False + assert module.gate_verdict({})["passed"] is False + + +def test_smoke_dataset_is_valid_yolo(smoke_data: Path) -> None: + """The throwaway generator emits in-bounds labels, only schema class ids, and the three splits.""" + cfg = train.load_data_yaml(smoke_data) + assert train.dataset_names(cfg)[:2] == ["NMOS", "PMOS"] + for split, key in (("train", "train"), ("valid", "val"), ("test", "test")): + images = train.split_images(cfg, smoke_data, key) + assert images, split + for image in images: + rows = [r.split() for r in (smoke_data.parent / "labels" / split / f"{image.stem}.txt").read_text().splitlines()] + assert rows and all(0 <= int(r[0]) < 14 and all(0.0 < float(v) <= 1.0 for v in r[1:]) for r in rows) + + +@pytest.mark.smoke +@pytest.mark.skipif(os.environ.get("DIGISIM_ML_SMOKE") != "1", reason="set DIGISIM_ML_SMOKE=1 to run the 2-epoch CPU training smoke test (downloads yolov8n.pt)") +def test_cpu_smoke_run_produces_metrics_and_onnx(tmp_path: Path) -> None: + """2 epochs of the smoke preset on a 200-image throwaway set finish on CPU and write metrics.json plus an ONNX file.""" + data = make_smoke_dataset.generate(tmp_path / "ds", 200, seed=0) + proc = subprocess.run( + [sys.executable, str(ML_DIR / "train.py"), "--preset", "smoke", "--data", str(data), "--device", "cpu", "--workers", "2", "--project", str(tmp_path / "runs"), "--name", "smoke"], + cwd=ML_DIR, + capture_output=True, + text=True, + timeout=1800, + env={**os.environ, "OMP_NUM_THREADS": "4", "YOLO_OFFLINE": os.environ.get("YOLO_OFFLINE", "")}, + ) + assert proc.returncode == 0, proc.stdout[-2000:] + proc.stderr[-2000:] + run = tmp_path / "runs" / "smoke" + metrics = json.loads((run / "metrics.json").read_text()) + assert metrics["schema_version"] == 1 and metrics["preset"] == "smoke" and metrics["settings"]["epochs"] == 2 + assert metrics["dataset"]["train_images"] == 140 and len(metrics["class_names"]) == 14 + assert (run / "best.pt").stat().st_size > 0 + assert (run / "best.onnx").stat().st_size > 0 diff --git a/ml/train.py b/ml/train.py index 6eb447a..d8884a0 100644 --- a/ml/train.py +++ b/ml/train.py @@ -1,114 +1,766 @@ """ Module: train.py -Purpose: Trains the DigiSim gate detector via YOLOv8 transfer learning (pretrained - COCO weights — never random init) on the merged synthetic + hand-drawn - dataset. Logs every run to ml/experiments/run_YYYYMMDD_HHMM/ with - config.yaml, metrics.json and notes.md, and copies best weights to - backend/model/weights/best.pt for the inference pipeline. +Purpose: Trains the DigiSim symbol detector via YOLO transfer learning (pretrained weights - + never random init) on CPU, one GPU or several GPUs (DDP) with the same command. + Two presets drive the real pipeline: `stage-a` (synthetic pretrain) and `stage-b` + (mixed fine-tune of the stage-A weights with real images oversampled); `smoke` is a + 2-epoch CPU check. Every run writes a flat artifact folder (config.yaml, notes.md, + best.pt, best.onnx, metrics.json) under ml/experiments/ (gitignored) and can be + resumed. ml/kaggle/train_kaggle.py is the single-file Kaggle twin of this harness. Usage: - cd ml && uv run python train.py [--epochs 60] [--imgsz 416] [--notes "..."] + cd ml + uv run python train.py --preset smoke --data /path/to/data.yaml --device cpu + uv run python train.py --preset stage-a --data /path/to/synthetic/data.yaml --device 0,1,2,3 + uv run python train.py --preset stage-b --data /path/to/mixed/data.yaml --model runs/stage_a/best.pt --real-train /path/to/real/images/train + uv run python train.py --preset stage-a --data data.yaml --device 0,1,2,3 --dry-run # print the plan, train nothing + uv run python train.py --resume experiments/run_YYYYMMDD_HHMM # continue an interrupted run """ import argparse import json +import os +import platform import shutil +import sys +import time +from collections.abc import Iterable, Sequence +from dataclasses import dataclass from datetime import datetime from pathlib import Path +from typing import Any +import numpy as np import yaml -from ultralytics import YOLO + +from class_schema import TIER_ORDER, load_schema ML_DIR = Path(__file__).resolve().parent REPO_ROOT = ML_DIR.parent +DEFAULT_PROJECT = ML_DIR / "experiments" DEFAULT_DATA = ML_DIR / "dataset" / "data.yaml" WEIGHTS_DST = REPO_ROOT / "backend" / "model" / "weights" / "best.pt" +IMAGE_SUFFIXES = frozenset({".jpg", ".jpeg", ".png", ".bmp", ".webp"}) +F1_THRESHOLD = 0.95 +ACC_THRESHOLD = 0.95 +METRICS_SCHEMA_VERSION = 1 +ONNX_OPSET = 17 +SEED = 0 + + +@dataclass(frozen=True) +class Preset: + """Default hyper-parameters of one training stage; every field can be overridden on the CLI.""" + + name: str + description: str + model: str | None + imgsz: int + epochs: int + batch_per_device: int + patience: int + lr0: float + lrf: float + warmup_epochs: float + close_mosaic: int + real_oversample: int + plots: bool + + +PRESETS: dict[str, Preset] = { + "smoke": Preset("smoke", "2-epoch CPU check of the whole harness (train, val, ONNX export, metrics.json)", "yolov8n.pt", 320, 2, 8, 2, 0.01, 0.01, 0.0, 0, 1, False), + "stage-a": Preset("stage-a", "synthetic pretrain: COCO-pretrained yolov8s on synthetic data", "yolov8s.pt", 960, 100, 16, 20, 0.01, 0.01, 3.0, 10, 1, True), + "stage-b": Preset("stage-b", "mixed fine-tune: continue from the stage-A weights with real images oversampled", None, 960, 40, 16, 15, 0.002, 0.1, 1.0, 5, 4, True), +} +DEFAULT_PRESET = "stage-a" + + +@dataclass(frozen=True) +class DevicePlan: + """A resolved compute target: the CPU, or one or more CUDA device indices (more than one means DDP).""" + + ids: tuple[int, ...] + + @property + def is_cpu(self) -> bool: + """ + Whether training runs on the CPU. + + Returns: + True when no CUDA device was requested. + """ + return not self.ids + + @property + def world_size(self) -> int: + """ + Number of training processes (1 for CPU or a single GPU). + + Returns: + DDP world size. + """ + return max(1, len(self.ids)) + + @property + def spec(self) -> str: + """ + The device string handed to ultralytics. + + Returns: + 'cpu' or a comma-separated index list such as '0,1,2,3'. + """ + return "cpu" if self.is_cpu else ",".join(str(i) for i in self.ids) + + +@dataclass(frozen=True) +class TrainConfig: + """Fully resolved settings of one run (preset defaults merged with CLI overrides).""" + + preset: str + model: str + data: Path + project: Path + name: str + epochs: int + imgsz: int + batch: int + device: DevicePlan + workers: int + patience: int + lr0: float + lrf: float + warmup_epochs: float + close_mosaic: int + plots: bool + seed: int + real_train: tuple[Path, ...] + real_oversample: int + resume: Path | None + class_check: str + install_weights: bool + notes: str + + @property + def run_dir(self) -> Path: + """ + Directory that holds this run's artifacts. + + Returns: + project / name. + """ + return self.project / self.name + + +def default_workers() -> int: + """ + Default dataloader worker count derived from the CPUs this process may use. + + Returns: + A value in [1, 8] (the CPU count, capped; cgroup/affinity aware where the OS exposes it). + """ + try: + cpus = len(os.sched_getaffinity(0)) + except AttributeError: # not available on macOS / Windows + cpus = os.cpu_count() or 1 + return max(1, min(8, cpus)) + + +def detect_cuda_count() -> int: + """ + Count visible CUDA devices without requiring torch to be installed. + + Returns: + Number of CUDA devices, 0 when torch is missing or no GPU is visible. + """ + try: + import torch + except ImportError: + return 0 + return int(torch.cuda.device_count()) + + +def parse_device(spec: str, cuda_count: int | None = None) -> DevicePlan: + """ + Parse a --device value into a DevicePlan (pure string handling, so it works without a GPU). + + Args: + spec: 'cpu', 'auto' (all visible GPUs, else CPU), '0', or a comma list like '0,1,2,3'. + cuda_count: Visible GPU count used by 'auto'; detected via torch when None. + Returns: + The resolved plan. + Raises: + ValueError: If the spec is empty, malformed, negative or lists a device twice. + """ + text = spec.strip().lower().replace(" ", "") + if text == "cpu": + return DevicePlan(()) + if text == "auto": + count = detect_cuda_count() if cuda_count is None else cuda_count + return DevicePlan(tuple(range(count))) + parts = [p for p in text.removeprefix("cuda:").split(",") if p != ""] + try: + ids = tuple(int(p.removeprefix("cuda:")) for p in parts) + except ValueError as exc: + raise ValueError(f"Bad --device {spec!r}: use 'cpu', 'auto', '0' or '0,1,2,3'") from exc + if not ids or any(i < 0 for i in ids) or len(set(ids)) != len(ids): + raise ValueError(f"Bad --device {spec!r}: need unique non-negative device indices") + return DevicePlan(ids) + + +def resolve_batch(requested: int | None, per_device: int, plan: DevicePlan) -> int: + """ + Resolve the total batch size (ultralytics splits it evenly across DDP processes). + + Args: + requested: Total batch from --batch, or None for per-device default x world size. + per_device: Preset batch per device. + plan: Resolved device plan. + Returns: + The total batch size. + Raises: + ValueError: If the batch is not positive or not divisible by the GPU count (-1 auto-batch is single-device only). + """ + batch = per_device * plan.world_size if requested is None else requested + if batch == -1 and plan.world_size == 1: + return batch + if batch < 1: + raise ValueError(f"batch must be >= 1 (got {batch}); -1 auto-batch is single-device only") + if batch % plan.world_size: + raise ValueError(f"batch {batch} must be a multiple of the GPU count {plan.world_size} for DDP") + return batch + + +def load_data_yaml(path: Path) -> dict[str, object]: + """ + Read a YOLO dataset yaml. + + Args: + path: Path to data.yaml. + Returns: + The parsed mapping. + Raises: + FileNotFoundError: If the file does not exist. + ValueError: If it is not a mapping with train, val and names. + """ + if not path.is_file(): + raise FileNotFoundError(f"{path} not found - generate a dataset first (class_schema.py data-yaml writes the yaml for it)") + cfg = yaml.safe_load(path.read_text()) + if not isinstance(cfg, dict) or not {"train", "val", "names"} <= cfg.keys(): + raise ValueError(f"{path}: expected a YOLO data.yaml with train, val and names") + return cfg + + +def dataset_names(cfg: dict[str, object]) -> list[str]: + """ + Class names of a data.yaml in id order (list or {id: name} form). + + Args: + cfg: Parsed data.yaml. + Returns: + Names indexed by class id. + Raises: + ValueError: If names is neither a list nor a mapping, or ids are not contiguous from 0. + """ + names = cfg["names"] + if isinstance(names, dict): + if sorted(int(k) for k in names) != list(range(len(names))): + raise ValueError("data.yaml names ids must be contiguous from 0") + return [str(names[k]) for k in sorted(names, key=int)] + if isinstance(names, list): + return [str(n) for n in names] + raise ValueError("data.yaml names must be a list or an {id: name} mapping") + + +def check_class_vocabulary(names: Sequence[str]) -> str: + """ + Verify a dataset uses the canonical vocabulary from ml/classes.yaml (a full tier prefix). + + Args: + names: Class names in id order from the dataset yaml. + Returns: + The tier ('A' or 'B') whose class list matches. + Raises: + ValueError: If the names match no tier, i.e. the dataset drifted from classes.yaml. + """ + schema = load_schema() + for tier in TIER_ORDER: + if list(names) == [c.name for c in schema.classes_up_to(tier)]: + return tier + raise ValueError(f"Dataset classes {list(names)} do not match ml/classes.yaml tier A or B; regenerate data.yaml with `class_schema.py data-yaml` (or pass --class-check off)") + + +def list_images(entries: Iterable[Path]) -> list[Path]: + """ + Expand image files, image directories and .txt image lists into a sorted image list. + + Args: + entries: Paths to images, directories (searched recursively) or .txt lists (one path per line). + Returns: + Absolute image paths, de-duplicated, sorted. + """ + found: set[Path] = set() + for entry in entries: + if entry.is_dir(): + found.update(p.resolve() for p in entry.rglob("*") if p.suffix.lower() in IMAGE_SUFFIXES) + elif entry.suffix == ".txt" and entry.is_file(): + for line in entry.read_text().splitlines(): + if line.strip(): + p = Path(line.strip()) + found.add((entry.parent / p if not p.is_absolute() else p).resolve()) + elif entry.suffix.lower() in IMAGE_SUFFIXES and entry.is_file(): + found.add(entry.resolve()) + return sorted(found) + + +def split_images(cfg: dict[str, object], data_yaml: Path, split: str) -> list[Path]: + """ + Images of one split of a dataset yaml (empty when the split is not declared). + + Args: + cfg: Parsed data.yaml. + data_yaml: Where the yaml lives (relative `path:` values resolve against its folder). + split: 'train', 'val' or 'test'. + Returns: + Sorted absolute image paths. + """ + value = cfg.get(split) + if not value: + return [] + root = Path(str(cfg["path"])) if cfg.get("path") else data_yaml.parent + if not root.is_absolute(): + root = data_yaml.parent / root + items = value if isinstance(value, list) else [value] + return list_images(root / str(item) for item in items) -def train(args: argparse.Namespace) -> Path: +def build_mixed_dataset(data_yaml: Path, real_dirs: Sequence[Path], factor: int, out_dir: Path) -> Path: """ - Run one training experiment and log it. + Write a derived data yaml whose train list repeats real images `factor` times (stage-B oversampling). Args: - args: Parsed CLI arguments (data, model, epochs, imgsz, batch, notes). + data_yaml: The base dataset yaml (synthetic plus whatever real images it already lists). + real_dirs: Image folders (or .txt lists) holding the real training images. + factor: How often each real image appears per epoch (1 = no oversampling). + out_dir: Where train_mixed.txt and data_mixed.yaml are written. Returns: - Path to the experiment run directory. + Path of the derived data yaml. Raises: - FileNotFoundError: If the dataset yaml does not exist. + ValueError: If factor < 1, no real image was found, or a real image is also in val/test (leakage). + """ + if factor < 1: + raise ValueError("real oversample factor must be >= 1") + cfg = load_data_yaml(data_yaml) + real = list_images(real_dirs) + if not real: + raise ValueError(f"No images found under --real-train {[str(d) for d in real_dirs]}") + held_out = set(split_images(cfg, data_yaml, "val")) | set(split_images(cfg, data_yaml, "test")) + leaked = sorted(held_out & set(real)) + if leaked: + raise ValueError(f"{len(leaked)} real training image(s) are also in val/test, e.g. {leaked[0]}") + real_set = set(real) + lines = [str(p) for p in split_images(cfg, data_yaml, "train") if p not in real_set] + lines += [str(p) for p in real for _ in range(factor)] + out_dir.mkdir(parents=True, exist_ok=True) + train_list = out_dir / "train_mixed.txt" + train_list.write_text("\n".join(lines) + "\n") + root = Path(str(cfg["path"])) if cfg.get("path") else data_yaml.parent + derived = {**cfg, "path": str((root if root.is_absolute() else data_yaml.parent / root).resolve()), "train": str(train_list)} + out_yaml = out_dir / "data_mixed.yaml" + out_yaml.write_text(yaml.safe_dump(derived, sort_keys=False)) + return out_yaml + + +def resolve_resume_checkpoint(target: Path) -> Path: + """ + Locate last.pt from a run directory, a train directory or the checkpoint itself. + + Args: + target: A run dir, its train/ subdir, or a last.pt path. + Returns: + Path to last.pt. + Raises: + FileNotFoundError: If no checkpoint is found. + """ + for candidate in (target, target / "weights" / "last.pt", target / "train" / "weights" / "last.pt", target / "last.pt"): + if candidate.is_file() and candidate.suffix == ".pt": + return candidate + raise FileNotFoundError(f"No last.pt checkpoint found for --resume {target}") + + +def load_saved_config(run_dir: Path) -> dict[str, object]: + """ + Read the config.yaml a previous run wrote, so --resume can reuse its preset, data and image size. + + Args: + run_dir: The run directory. + Returns: + The saved mapping, empty when the run has no readable config.yaml. """ - if not args.data.exists(): - raise FileNotFoundError(f"{args.data} not found — run backend/data_gen/screenshot_pipeline.py") + path = run_dir / "config.yaml" + if not path.is_file(): + return {} + loaded = yaml.safe_load(path.read_text()) + return loaded if isinstance(loaded, dict) else {} + - run_name = f"run_{datetime.now():%Y%m%d_%H%M}" - run_dir = ML_DIR / "experiments" / run_name +def resolve_config(args: argparse.Namespace) -> TrainConfig: + """ + Merge the preset defaults with CLI overrides and validate the combination. + + Args: + args: Parsed CLI arguments. + Returns: + The resolved TrainConfig. + Raises: + ValueError: If the device, batch, stage-B model or oversample settings are invalid. + FileNotFoundError: If --resume points at nothing. + """ + plan = parse_device(args.device) + 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) + 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 + if oversample > 1 and not real_train: + raise ValueError("--real-oversample needs at least one --real-train folder") + return TrainConfig( + preset=preset.name, + model=model, + data=args.data or Path(str(saved.get("data") or DEFAULT_DATA)), + project=resume.parent.parent.parent.parent if resume else args.project, + 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), + 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), + lr0=args.lr0 if args.lr0 is not None else float(saved.get("lr0") or preset.lr0), + lrf=preset.lrf, + warmup_epochs=preset.warmup_epochs, + close_mosaic=preset.close_mosaic, + plots=preset.plots if args.plots is None else args.plots, + seed=args.seed if args.seed is not None else int(saved.get("seed") or SEED), + real_train=real_train, + real_oversample=oversample, + resume=resume, + class_check=args.class_check, + install_weights=args.install_weights, + notes=args.notes, + ) + + +def describe_plan(cfg: TrainConfig) -> dict[str, object]: + """ + Build the dry-run report: resolved settings, launch topology and dataset sanity (never raises on dataset problems). + + Args: + cfg: Resolved configuration. + Returns: + JSON-serialisable plan. + """ + warnings: list[str] = [] + dataset: dict[str, object] = {"data": str(cfg.data)} + try: + data_cfg = load_data_yaml(cfg.data) + names = dataset_names(data_cfg) + dataset["classes"] = len(names) + dataset["eval_split"] = "test" if data_cfg.get("test") else "val" + for split in ("train", "val", "test"): + dataset[f"{split}_images"] = len(split_images(data_cfg, cfg.data, split)) + if cfg.class_check == "strict": + dataset["tier"] = check_class_vocabulary(names) + if not dataset["train_images"]: + warnings.append("train split has no images") + except (FileNotFoundError, ValueError) as exc: + warnings.append(f"dataset: {exc}") + if cfg.model.endswith(".pt") and not Path(cfg.model).is_file() and cfg.resume is None and Path(cfg.model).name == cfg.model: + warnings.append(f"{cfg.model} is a pretrained-weights name that ultralytics downloads on first use") + return { + "preset": cfg.preset, + "model": cfg.model, + "device": {"spec": cfg.device.spec, "cpu": cfg.device.is_cpu, "world_size": cfg.device.world_size, "ddp": cfg.device.world_size > 1}, + "batch_total": cfg.batch, + "batch_per_process": cfg.batch // cfg.device.world_size if cfg.batch > 0 else cfg.batch, + "workers": cfg.workers, + "epochs": cfg.epochs, + "imgsz": cfg.imgsz, + "lr0": cfg.lr0, + "patience": cfg.patience, + "real_train": [str(p) for p in cfg.real_train], + "real_oversample": cfg.real_oversample, + "resume": str(cfg.resume) if cfg.resume else None, + "run_dir": str(cfg.run_dir), + "dataset": dataset, + "warnings": warnings, + } + + +def per_class_metrics(box: Any, names: dict[int, str], confusion: Any, instances: Any) -> dict[str, dict[str, float]]: + """ + Per-class precision/recall/F1/AP/accuracy from an ultralytics validation result. + + Accuracy follows ml/evaluate.py: confusion-matrix TP divided by all ground-truth boxes of the class. + + Args: + box: The `metrics.box` object (p, r, f1, ap50, ap, ap_class_index arrays; ultralytics is duck-typed here). + names: Class id to name map of the model. + confusion: The validator confusion matrix (matrix[pred, gt]) or None. + instances: Per-class ground-truth counts array or None. + Returns: + Class name to metric dict; classes absent from the evaluated split are omitted. + """ + idx = np.atleast_1d(getattr(box, "ap_class_index", [])).astype(int) + columns = {key: np.atleast_1d(getattr(box, attr, np.zeros(len(idx)))) for key, attr in (("precision", "p"), ("recall", "r"), ("f1", "f1"), ("ap50", "ap50"), ("ap50_95", "ap"))} + counts = None if instances is None else np.atleast_1d(instances) + matrix = getattr(confusion, "matrix", None) + out: dict[str, dict[str, float]] = {} + for pos, cls_id in enumerate(idx): + entry = {key: float(col[pos]) for key, col in columns.items()} + if counts is not None and cls_id < len(counts): + entry["instances"] = float(counts[cls_id]) + if matrix is not None and cls_id < matrix.shape[1] and matrix[:, cls_id].sum() > 0: + entry["accuracy"] = float(matrix[cls_id, cls_id]) / float(matrix[:, cls_id].sum()) + out[names[int(cls_id)]] = entry + return out + + +def gate_verdict(per_class: dict[str, dict[str, float]]) -> dict[str, object]: + """ + Apply the AGENTS.md phase gate (F1 >= 0.95 and accuracy >= 0.95 per class) to a per-class table. + + Args: + per_class: Output of per_class_metrics(). + Returns: + Thresholds, failing class names and the overall pass flag (False when nothing was evaluated). + """ + failing = [n for n, m in per_class.items() if m.get("f1", 0.0) < F1_THRESHOLD or m.get("accuracy", 0.0) < ACC_THRESHOLD] + return {"f1_threshold": F1_THRESHOLD, "accuracy_threshold": ACC_THRESHOLD, "failing_classes": failing, "passed": bool(per_class) and not failing} + + +def environment_info() -> dict[str, object]: + """ + Describe the software and hardware the run executed on. + + Returns: + Versions, CPU count and visible GPU names (torch/ultralytics entries are None when not importable). + """ + info: dict[str, object] = {"python": platform.python_version(), "platform": platform.platform(), "cpu_count": os.cpu_count(), "torch": None, "ultralytics": None, "cuda_devices": []} + try: + import torch + + info["torch"] = torch.__version__ + info["cuda_devices"] = [torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())] + except ImportError: + pass + try: + import ultralytics + + info["ultralytics"] = ultralytics.__version__ + except ImportError: + pass + return info + + +def config_dict(cfg: TrainConfig, data_effective: Path) -> dict[str, object]: + """ + Flatten a TrainConfig into a YAML-friendly dict for config.yaml. + + Args: + cfg: Resolved configuration. + data_effective: The data yaml actually trained on (differs from cfg.data when oversampling). + Returns: + Plain-typed mapping (paths as strings, device expanded). + """ + out: dict[str, object] = {} + for key, value in vars(cfg).items(): + if key == "device": + out["device"], out["world_size"] = cfg.device.spec, cfg.device.world_size + elif isinstance(value, Path): + out[key] = str(value) + elif isinstance(value, tuple): + out[key] = [str(v) for v in value] + else: + out[key] = value + out["data_effective"] = str(data_effective) + return out + + +def train(cfg: TrainConfig) -> Path: + """ + Run one training experiment end to end: train, validate best.pt, export ONNX, write metrics.json. + + Args: + cfg: Resolved configuration (see resolve_config). + Returns: + The run directory holding config.yaml, notes.md, best.pt, best.onnx and metrics.json. + Raises: + FileNotFoundError: If the dataset yaml is missing. + ValueError: If the dataset classes drift from classes.yaml (unless --class-check off) or real-image leakage is found. + """ + from ultralytics import YOLO + + data_cfg = load_data_yaml(cfg.data) + if cfg.class_check == "strict": + check_class_vocabulary(dataset_names(data_cfg)) + run_dir = cfg.run_dir run_dir.mkdir(parents=True, exist_ok=True) - config = { - "base_model": args.model, - "data": str(args.data), - "epochs": args.epochs, - "imgsz": args.imgsz, - "batch": args.batch, - "device": "cpu", - "patience": args.patience, - "seed": 0, + data_yaml = cfg.data + if cfg.real_train: + data_yaml = build_mixed_dataset(cfg.data, cfg.real_train, cfg.real_oversample, run_dir) + (run_dir / "config.yaml").write_text(yaml.safe_dump(config_dict(cfg, data_yaml), sort_keys=False)) + if not (run_dir / "notes.md").exists(): + (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 + train_kwargs: dict[str, object] = { + "data": str(data_yaml), + "epochs": cfg.epochs, + "imgsz": cfg.imgsz, + "batch": cfg.batch, + "device": cfg.device.spec, + "workers": cfg.workers, + "patience": cfg.patience, + "seed": cfg.seed, + "lr0": cfg.lr0, + "lrf": cfg.lrf, + "warmup_epochs": cfg.warmup_epochs, + "close_mosaic": cfg.close_mosaic, + "plots": cfg.plots, + "project": str(run_dir), + "name": "train", + "exist_ok": True, } - (run_dir / "config.yaml").write_text(yaml.safe_dump(config)) - (run_dir / "notes.md").write_text(f"# {run_name}\n\n{args.notes or 'No notes provided.'}\n") - - model = YOLO(args.model) # transfer learning from pretrained COCO weights - model.train( - data=str(args.data), - epochs=args.epochs, - imgsz=args.imgsz, - batch=args.batch, - device="cpu", - workers=args.workers, - patience=args.patience, - seed=0, + 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) + else: + model.train(**train_kwargs) + trainer = model.trainer + best = Path(trainer.best) if Path(trainer.best).is_file() else Path(trainer.last) + save_dir = Path(trainer.save_dir) + + eval_split = "test" if data_cfg.get("test") else "val" + eval_device = "cpu" if cfg.device.is_cpu else str(cfg.device.ids[0]) # final validation is single-process even after DDP + best_model = YOLO(str(best)) + val = best_model.val( + data=str(data_yaml), + split=eval_split, + imgsz=cfg.imgsz, + batch=min(cfg.batch, 16) if cfg.batch > 0 else 16, + device=eval_device, + workers=0, + plots=True, project=str(run_dir), - name="train", + name="val", exist_ok=True, - plots=True, ) + per_class = per_class_metrics(val.box, best_model.names, getattr(val, "confusion_matrix", None), getattr(val, "nt_per_class", None)) + onnx_src = Path(best_model.export(format="onnx", imgsz=cfg.imgsz, opset=ONNX_OPSET, simplify=True, dynamic=False, device="cpu")) - best = run_dir / "train" / "weights" / "best.pt" - metrics = model.val(data=str(args.data), split="test", device="cpu", plots=True) - summary = { - "map50": float(metrics.box.map50), - "map50_95": float(metrics.box.map), - "mean_precision": float(metrics.box.mp), - "mean_recall": float(metrics.box.mr), - "weights": str(best), + shutil.copy2(best, run_dir / "best.pt") + shutil.copy2(onnx_src, run_dir / "best.onnx") + summary: dict[str, object] = { + "schema_version": METRICS_SCHEMA_VERSION, + "run_name": cfg.name, + "preset": cfg.preset, + "map50": float(val.box.map50), + "map50_95": float(val.box.map), + "mean_precision": float(val.box.mp), + "mean_recall": float(val.box.mr), + "eval_split": eval_split, + "per_class": per_class, + "gate": gate_verdict(per_class), + "class_names": [best_model.names[i] for i in sorted(best_model.names)], + "dataset": { + "data": str(cfg.data), + "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")), + "real_oversample": cfg.real_oversample, + }, + "settings": {"model": cfg.model, "epochs": cfg.epochs, "imgsz": cfg.imgsz, "batch": cfg.batch, "device": cfg.device.spec, "workers": cfg.workers, "seed": cfg.seed, "lr0": cfg.lr0}, + "environment": environment_info(), + "train_seconds": round(time.time() - started, 1), + "weights": str(run_dir / "best.pt"), + "onnx": str(run_dir / "best.onnx"), + "ultralytics_run_dir": str(save_dir), } (run_dir / "metrics.json").write_text(json.dumps(summary, indent=2)) - - WEIGHTS_DST.parent.mkdir(parents=True, exist_ok=True) - shutil.copy2(best, WEIGHTS_DST) - print(f"\nRun logged to {run_dir}") - print(f"Best weights copied to {WEIGHTS_DST}") - print("Run `uv run python evaluate.py` for per-class F1/accuracy.") + if cfg.install_weights: + WEIGHTS_DST.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(best, WEIGHTS_DST) + print(f"Best weights installed at {WEIGHTS_DST}") + print(f"\nRun logged to {run_dir} (best.pt, best.onnx, metrics.json)") + print("Run `uv run python evaluate.py` for the per-class F1/accuracy gate.") return run_dir -def main() -> None: +def build_parser() -> argparse.ArgumentParser: + """ + Build the CLI parser (all tunables default to None so presets can fill them in). + + Returns: + The configured parser. + """ + p = argparse.ArgumentParser(description="Train the DigiSim symbol detector (CPU, GPU or multi-GPU DDP)") + p.add_argument("--preset", choices=sorted(PRESETS), default=None, help=f"default {DEFAULT_PRESET} (or the resumed run's preset). " + "; ".join(f"{k}: {v.description}" for k, v in PRESETS.items())) + p.add_argument("--data", type=Path, default=None, help="YOLO data.yaml (default: the resumed run's data, else ml/dataset/data.yaml)") + p.add_argument("--model", default=None, help="pretrained .pt to start from (stage-b: the stage-A best.pt)") + p.add_argument("--device", default="auto", help="cpu | auto | 0 | 0,1,2,3 (several indices = DDP)") + p.add_argument("--epochs", type=int, default=None) + p.add_argument("--imgsz", type=int, default=None) + p.add_argument("--batch", type=int, default=None, help="TOTAL batch across devices (default: preset per-device batch x GPUs)") + p.add_argument("--workers", type=int, default=None, help="dataloader workers (default: usable CPU count, max 8)") + p.add_argument("--patience", type=int, default=None) + p.add_argument("--lr0", type=float, default=None) + p.add_argument("--seed", type=int, default=None, help=f"default {SEED} (or the resumed run's seed)") + p.add_argument("--plots", action=argparse.BooleanOptionalAction, default=None) + p.add_argument("--real-train", type=Path, action="append", default=[], help="real training image folder/list to oversample (repeatable)") + p.add_argument("--real-oversample", type=int, default=None, help="times each real image repeats per epoch (stage-b default 4)") + p.add_argument("--resume", type=Path, default=None, help="run dir, train dir or last.pt of an interrupted run; reuses its saved config.yaml and run folder") + p.add_argument("--project", type=Path, default=DEFAULT_PROJECT, help="parent folder of run dirs") + p.add_argument("--name", default=None, help="run folder name (default run_YYYYMMDD_HHMM)") + p.add_argument("--class-check", choices=("strict", "off"), default="strict", help="require data.yaml names to equal ml/classes.yaml tier A or B") + p.add_argument("--install-weights", action="store_true", help=f"also copy best.pt to {WEIGHTS_DST.relative_to(REPO_ROOT)}") + p.add_argument("--notes", default="") + p.add_argument("--dry-run", action="store_true", help="print the resolved plan as JSON and exit without importing torch/ultralytics") + return p + + +def main(argv: Sequence[str] | None = None) -> int: """ CLI entry point. - Raises: - SystemExit: On argparse errors. + Args: + argv: Argument list (defaults to sys.argv[1:]). + Returns: + Process exit code (0 on success, 2 on invalid configuration). """ - parser = argparse.ArgumentParser(description="Train DigiSim gate detector") - parser.add_argument("--data", type=Path, default=DEFAULT_DATA) - parser.add_argument("--model", default="yolov8n.pt") - parser.add_argument("--epochs", type=int, default=60) - parser.add_argument("--imgsz", type=int, default=416) - parser.add_argument("--batch", type=int, default=16) - parser.add_argument("--workers", type=int, default=8) - parser.add_argument("--patience", type=int, default=15) - parser.add_argument("--notes", default="") - train(parser.parse_args()) + args = build_parser().parse_args(argv) + try: + cfg = resolve_config(args) + except (ValueError, FileNotFoundError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + if args.dry_run: + print(json.dumps(describe_plan(cfg), indent=2)) + return 0 + try: + train(cfg) + except (ValueError, FileNotFoundError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 + return 0 if __name__ == "__main__": - main() + sys.exit(main()) diff --git a/ml/uv.lock b/ml/uv.lock index b4e6f90..48119d8 100644 --- a/ml/uv.lock +++ b/ml/uv.lock @@ -2,8 +2,12 @@ version = 1 revision = 5 requires-python = ">=3.11" resolution-markers = [ - "python_full_version >= '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.12' and sys_platform != 'win32'", + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'win32'", "python_full_version < '3.12' and sys_platform == 'win32'", "python_full_version < '3.12' and sys_platform != 'win32'", ] @@ -305,6 +309,9 @@ dependencies = [ { name = "huggingface-hub" }, { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "numpy", version = "2.5.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "onnx" }, + { name = "onnxruntime" }, + { name = "onnxslim" }, { name = "opencv-python-headless" }, { name = "pillow" }, { name = "pyyaml" }, @@ -323,6 +330,9 @@ dev = [ requires-dist = [ { name = "huggingface-hub", specifier = ">=0.24" }, { name = "numpy", specifier = ">=1.26" }, + { name = "onnx", specifier = ">=1.16" }, + { name = "onnxruntime", specifier = ">=1.18" }, + { name = "onnxslim", specifier = ">=0.1.34" }, { name = "opencv-python-headless", specifier = ">=4.9" }, { name = "pillow", specifier = ">=10.1" }, { name = "pyyaml", specifier = ">=6.0" }, @@ -345,6 +355,14 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/4a/e3/f1fae3647d170919c2cf2a898e77e7d1a4e5c7cae0aed7bb4bd3f5ebff6f/filelock-3.29.5-py3-none-any.whl", hash = "sha256:8af830889ba3a0ffcefbd6c7d2af8a54012058103771f2e10848222f476a1693", size = 45073, upload-time = "2026-07-03T03:50:30.445Z" }, ] +[[package]] +name = "flatbuffers" +version = "25.12.19" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e8/2d/d2a548598be01649e2d46231d151a6c56d10b964d94043a335ae56ea2d92/flatbuffers-25.12.19-py2.py3-none-any.whl", hash = "sha256:7634f50c427838bb021c2d66a3d1168e9d199b0607e6329399f04846d42e20b4", size = 26661, upload-time = "2025-12-19T23:16:13.622Z" }, +] + [[package]] name = "fonttools" version = "4.63.0" @@ -770,6 +788,53 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/0c/d8/c4ecab06b7ea36a570c4f3bd2d48d1799fd5d9174470e45c2194199431e7/matplotlib-3.11.0-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cf662e5ac5707658cb931e19972c4bd99f7b4f8b7bf79d3c821d239fa6b71e64", size = 10015653, upload-time = "2026-06-12T02:29:13.251Z" }, ] +[[package]] +name = "ml-dtypes" +version = "0.7.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "numpy", version = "2.5.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bc/2d/4ce5532f433dfae6dc96ed4abd7a0e18106a63666bce8eb878d9ffdc0610/ml_dtypes-0.7.0.tar.gz", hash = "sha256:67fd890fb09d1e068cfe1b4dc8e204430ae7632102b4a4f854b093b6f02b3950", size = 4353024, upload-time = "2026-11-16T16:21:26.657Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/82/c2/634f85467e7fc2813ae52165a5e878b8b863ccb25c151b68b3eb40de1a12/ml_dtypes-0.7.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:8b50c4b98e4bfde3b86fa8a623658ff5fca13c42d936f8223ad8bcf82d6fa400", size = 737433, upload-time = "2026-11-16T16:20:32.292Z" }, + { url = "https://files.pythonhosted.org/packages/4d/82/5ccc768d22c4dd2c4869ae0266dbc41c6fcd8198429e401937539d99fd6d/ml_dtypes-0.7.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7c094b42cb01f21e37e602a5cfe502ddaf6b5c60f66a162fd1e61f9a586558cb", size = 438897, upload-time = "2026-11-16T16:20:33.639Z" }, + { url = "https://files.pythonhosted.org/packages/ed/ce/3e0eaaaca8e60ca12ec0ae396520d85a7ee4a132aa111e054accfa7c568d/ml_dtypes-0.7.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d214c910cabaf80aa1ee37b0f25131e20d7a6474182e5293a68985b0421299da", size = 467165, upload-time = "2026-11-16T16:20:35.069Z" }, + { url = "https://files.pythonhosted.org/packages/16/e0/b8749babde8d45345cd9a7147f7445794958f9b4a39c9020e0695af76d4f/ml_dtypes-0.7.0-cp311-cp311-win_amd64.whl", hash = "sha256:15fa56d3b2b31fce16c13935ff8693f95c42620fe0f81e93d1f2cdee19425540", size = 462925, upload-time = "2026-11-16T16:20:36.435Z" }, + { url = "https://files.pythonhosted.org/packages/72/8e/a34e9c490539cbe4806e011c3e5449fb2c243b5be747cbf7421d1db42515/ml_dtypes-0.7.0-cp311-cp311-win_arm64.whl", hash = "sha256:0302deb4c0c69555f29ca6741458155b302f8294e850f04358c8a07bcdb7caf5", size = 589325, upload-time = "2026-11-16T16:20:37.994Z" }, + { url = "https://files.pythonhosted.org/packages/6c/e4/5c1579cfac55dab603df1870be84fc270df32c1e81b96314976bf5814b26/ml_dtypes-0.7.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:3cfe29fc79a00f4555c5319a32c549c10ec075ec888974ab4c0a59598e1f0f48", size = 738779, upload-time = "2026-11-16T16:20:39.543Z" }, + { url = "https://files.pythonhosted.org/packages/9b/7c/39dd1b5b4458ea1c6d52f5161d92e78e723c05a33c172359dd420ca388be/ml_dtypes-0.7.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7366e3ac8630e2bb35e67945391889225e2221c581c0831ec01a8cf50de3461a", size = 436741, upload-time = "2026-11-16T16:20:41.443Z" }, + { url = "https://files.pythonhosted.org/packages/98/cc/d6949ae90ff708e8b9f1889f4e6bdb74c31b2603fa29936a97b52dd784fa/ml_dtypes-0.7.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3c4e47f553a04d33886160a9600e2313e5bee8c1c3da997baa23c8fecbfab189", size = 463670, upload-time = "2026-11-16T16:20:42.875Z" }, + { url = "https://files.pythonhosted.org/packages/60/21/3ca0cb91c528d6250d356e62645d868dc3276cb701cc194a2ae40ca99a83/ml_dtypes-0.7.0-cp312-cp312-win_amd64.whl", hash = "sha256:0b1d09c91aaa6f38052521d5377cecb1523f50d4aee7783183a955a6544b8ad6", size = 463335, upload-time = "2026-11-16T16:20:44.317Z" }, + { url = "https://files.pythonhosted.org/packages/61/e0/6d97837f234b658a4f553b59b95e24799a4bd8e544e536435d8e85e0f005/ml_dtypes-0.7.0-cp312-cp312-win_arm64.whl", hash = "sha256:b29d506d51d994efce5e1f214a6cab77d96b796c5ab59a63f23d9a8c5b20e4dd", size = 587991, upload-time = "2026-11-16T16:20:45.95Z" }, + { url = "https://files.pythonhosted.org/packages/38/64/e435533e50e407cd7f8cb9570f824c3e0e40463715cc6f4bfccf81632107/ml_dtypes-0.7.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:1c442cebb388bbe3bcebda9e3864bdbb719a2611742fdd72687b424b5b3a4080", size = 738753, upload-time = "2026-11-16T16:20:47.393Z" }, + { url = "https://files.pythonhosted.org/packages/c6/5d/4a429dad9a622aea8135c2bd38b4e8222119b4168292dd030b6df579f0c3/ml_dtypes-0.7.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9e0f30247d011782286f9f5b8b0a3fad3f4f945d2a92cb9964c68d566ed17878", size = 436745, upload-time = "2026-11-16T16:20:49.01Z" }, + { url = "https://files.pythonhosted.org/packages/dd/9c/7e9eea3d4ef6739b34f3038b910ea42c8655e4eea372d15d7a5601fc1bc6/ml_dtypes-0.7.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5fb56999e1a03f47af5583af4089e00d04b68f87d4fadd659a5927ecd7687c3d", size = 463634, upload-time = "2026-11-16T16:20:50.49Z" }, + { url = "https://files.pythonhosted.org/packages/05/57/f26eb770c89dd56fe29d6f4458c1c8e496afde034fe74fda403183f11dbc/ml_dtypes-0.7.0-cp313-cp313-win_amd64.whl", hash = "sha256:8251e1bd8f68ebf9be6b0cad5ff6acee0e1768f2f45d55addda1a727e81503bf", size = 463435, upload-time = "2026-11-16T16:20:52.025Z" }, + { url = "https://files.pythonhosted.org/packages/36/38/3a390b0a6ef3155fa1ebb8de3aa4d547ccb90d00bb9ecd57af011142df85/ml_dtypes-0.7.0-cp313-cp313-win_arm64.whl", hash = "sha256:4fbce28a66691c56bb48620349df20a157b2c1bc949a6a1ce60a395a2b23293c", size = 587907, upload-time = "2026-11-16T16:20:53.764Z" }, + { url = "https://files.pythonhosted.org/packages/98/71/51867a1a1bcdcbf15cbe905107c0bcff99844d38fba3e92a3fa19ea45e4d/ml_dtypes-0.7.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:364d3b29ef3d06cd7f6bdfd7bd235f8dba104d7aa0de77df31b804d47b7b904f", size = 739397, upload-time = "2026-11-16T16:20:55.174Z" }, + { url = "https://files.pythonhosted.org/packages/5c/9d/159b18f3e34d778dca919cbd029c569ed25db7909cb4eb94459a9192070a/ml_dtypes-0.7.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8be8a421dca82572fd554a026d42f8e7aec6c5c9ddae4bbc118cf04051d13445", size = 436711, upload-time = "2026-11-16T16:20:56.871Z" }, + { url = "https://files.pythonhosted.org/packages/25/d0/6e0cd52b806a81933e5628834c105147a59f8836e89fe45a29f34d88dca3/ml_dtypes-0.7.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d0e87fdd2d380fa32f45e117687070b0e312b9f9a431bb0555edcd3a7821cb1d", size = 465164, upload-time = "2026-11-16T16:20:58.28Z" }, + { url = "https://files.pythonhosted.org/packages/ac/39/9f9ba9765f64465d496370624e3027a6b20bf7cc43989c7007db9c58890b/ml_dtypes-0.7.0-cp314-cp314-win_amd64.whl", hash = "sha256:306a494aee4ec6e1fc88cd9d5ce8b84973edb0f05b884fcf3883cf3d79700ba5", size = 477502, upload-time = "2026-11-16T16:20:59.801Z" }, + { url = "https://files.pythonhosted.org/packages/2b/b5/4090a863b3ca541533a73183b1d561786ac2d793aa15b75c87996d3abfad/ml_dtypes-0.7.0-cp314-cp314-win_arm64.whl", hash = "sha256:f5472be87d269572fe6afe2daa46870ed86d1129270c52734fe8485b91b697b2", size = 603587, upload-time = "2026-11-16T16:21:01.542Z" }, + { url = "https://files.pythonhosted.org/packages/7a/80/881830499809b4b98e79a825569511bfda092b52b1ad9a4738ac827c1b4a/ml_dtypes-0.7.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:dc7ac1da0f25d6deef1b37d5653e0b7df63e5396738d7da967a4f80a202fd51f", size = 759115, upload-time = "2026-11-16T16:21:02.97Z" }, + { url = "https://files.pythonhosted.org/packages/f2/3d/f2d7d4eace6493d10c4b302abd2e4552f3a378822cb315394857a75acefc/ml_dtypes-0.7.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:58828e7a44fdafb8380f98427fdccd418c12af2d875e00647439c832a1be5e14", size = 453112, upload-time = "2026-11-16T16:21:04.744Z" }, + { url = "https://files.pythonhosted.org/packages/89/78/c358bd8756d1a758f54aa8571776e5aef0eeee4b75a08c0883049890e883/ml_dtypes-0.7.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a34d838528a531724cfcb1ebd201c308176694e5dfa4fcebcfa2590fb96e7e12", size = 472215, upload-time = "2026-11-16T16:21:06.158Z" }, + { url = "https://files.pythonhosted.org/packages/ea/18/f614916d281090a598b0fa22004588b0e0bde3acf86675285280d69ef1a3/ml_dtypes-0.7.0-cp314-cp314t-win_amd64.whl", hash = "sha256:3a71fe4a4c323e89058ba828f41d3995203c27c09fed64776173de05e4ad28d1", size = 491626, upload-time = "2026-11-16T16:21:07.678Z" }, + { url = "https://files.pythonhosted.org/packages/39/0b/c47ba04c7113d3b9d13c56041021cbcbed07650ed7718c878843df2fc20e/ml_dtypes-0.7.0-cp314-cp314t-win_arm64.whl", hash = "sha256:69aeab7864e8a2beae8b4765945d44e826f82f8003a96a7c1cf3365b6abbaf2b", size = 608634, upload-time = "2026-11-16T16:21:09.058Z" }, + { url = "https://files.pythonhosted.org/packages/c5/2e/73636b53e1e50e530f63fdad2e48928e9fcb40d092f688b3ce2e305c5df2/ml_dtypes-0.7.0-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:6cc2f03294ca7fc24f231d6341e1f0afe53067cefa739b8c6d10614eb509c67b", size = 739386, upload-time = "2026-11-16T16:21:10.997Z" }, + { url = "https://files.pythonhosted.org/packages/36/c2/beb5c38452ea902096410fbe6456512ab31a0116c009f342eee376745981/ml_dtypes-0.7.0-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:92d06de5c9ffedb5e4c0809e9a3dec02f5457a9be864a89792f071b07d890a10", size = 436710, upload-time = "2026-11-16T16:21:12.684Z" }, + { url = "https://files.pythonhosted.org/packages/32/05/6d315f784aa5c0a8b54974dbfd5a9b2c995b1ff14aee48a4cfb9d246bdf7/ml_dtypes-0.7.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b24d45184f7508a160d69edf78dd2ed20c9b53f9f1064f52d96f3b800ed98371", size = 465156, upload-time = "2026-11-16T16:21:14.215Z" }, + { url = "https://files.pythonhosted.org/packages/39/78/bc623555aa81a017167f38449faeb57e945e36d9a8de5b5c36b16c695b1b/ml_dtypes-0.7.0-cp315-cp315-win_amd64.whl", hash = "sha256:9a8befe9c3610745515af48696044366b0e15accfcad12350c457fba5443ed21", size = 477450, upload-time = "2026-11-16T16:21:15.853Z" }, + { url = "https://files.pythonhosted.org/packages/01/36/66e6ced6f35986a504ab838b6c55d71f1b673a533a4993d64a7d80bcd120/ml_dtypes-0.7.0-cp315-cp315-win_arm64.whl", hash = "sha256:e621dfbc9bc7d75ded2782f58ff22f72eb9deb907e9f0fa09147eb3e6f4ae6aa", size = 603759, upload-time = "2026-11-16T16:21:17.283Z" }, + { url = "https://files.pythonhosted.org/packages/14/82/a848814ddb7c56eb1c6ca3258526a4c878fc68040416c176dc41dca6c55c/ml_dtypes-0.7.0-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:6b1b2c9d2acef9d47f157d47c9bbbe12df5814dd7642cd649ad08b4b6c29bb62", size = 758617, upload-time = "2026-11-16T16:21:18.908Z" }, + { url = "https://files.pythonhosted.org/packages/14/12/4ec20304ffe541f4e258ddd2b77349a6ee59fb79b66f231684ebbf2d2e9d/ml_dtypes-0.7.0-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:313629f5d5d34f419e9b789aa8c8afb4710126449cb12959be2a2f1980a7598a", size = 452397, upload-time = "2026-11-16T16:21:20.619Z" }, + { url = "https://files.pythonhosted.org/packages/9c/1d/082e098dd715e453fb4e9dcebaae581f9619f6b56f4cae0957335db50444/ml_dtypes-0.7.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0d0e6250683fe6fd30cdd161102c1c5eb8a04715667fba4e42a4690cbc104620", size = 472148, upload-time = "2026-11-16T16:21:22.031Z" }, + { url = "https://files.pythonhosted.org/packages/b8/81/5c8b4591b503f68122d08c82fffa58a75de14a4c9a3c61ab0d89830a3728/ml_dtypes-0.7.0-cp315-cp315t-win_amd64.whl", hash = "sha256:0f22e5b28370e2e9c5ce88b66a8ebab28009abbe6fdb8a089a7078c657eb2da9", size = 490371, upload-time = "2026-11-16T16:21:23.791Z" }, + { url = "https://files.pythonhosted.org/packages/8e/7d/0096f45dbfc6cebfd899bfa166aee40b89c8df121a76346a9ee9816704f2/ml_dtypes-0.7.0-cp315-cp315t-win_arm64.whl", hash = "sha256:118495dabbee38719343ce7bcaa7e33f503378c4694311791389375c1854aec8", size = 608942, upload-time = "2026-11-16T16:21:25.217Z" }, +] + [[package]] name = "mpmath" version = "1.3.0" @@ -876,8 +941,12 @@ name = "numpy" version = "2.5.0" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version >= '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.12' and sys_platform != 'win32'", + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'win32'", ] sdist = { url = "https://files.pythonhosted.org/packages/e7/05/3d27272d30698dc0ecb7fdfaa41ad70303b444f81722bb99bce1d818638a/numpy-2.5.0.tar.gz", hash = "sha256:5a129578019311b6e56bdd714250f19b518f7dceeeb8d1af5490f4942d3f891c", size = 20652461, upload-time = "2026-06-21T20:57:51.95Z" } wheels = [ @@ -1087,6 +1156,93 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a8/64/3708a90d1ebe202ffdeb7185f878a3c84d15c2b2c31858da2ce0583e2def/nvidia_nvtx-13.0.85-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cb7780edb6b14107373c835bf8b72e7a178bac7367e23da7acb108f973f157a6", size = 148878, upload-time = "2025-09-04T08:28:53.627Z" }, ] +[[package]] +name = "onnx" +version = "1.23.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "ml-dtypes" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "numpy", version = "2.5.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "protobuf" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/3f/62/bc2dfadb63ecf04cb2d65a6b17751863039d36c65de51d6a3128ab35f1e7/onnx-1.23.2.tar.gz", hash = "sha256:008cb0467b2bbee41448acc7da8b6f4e704624cb0d327a2d5adafc7ce19bc5b8", size = 6023090, upload-time = "2026-10-06T04:25:58.681Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ea/27/b8793ea89e16ce16beb0e662d29ee8f4e100e9e95202968d08f1c08795d3/onnx-1.23.2-cp311-cp311-macosx_13_0_universal2.whl", hash = "sha256:419bbbe3fbdf45a7658ee0aa1a54cd170ea15f3e5a60ace6e8d94f1577b3674b", size = 9725398, upload-time = "2026-10-06T04:25:21.31Z" }, + { url = "https://files.pythonhosted.org/packages/8a/2c/f9a5f186da571c396b660f97cc0e1aa85c5b76249abacda3de01b9f2e049/onnx-1.23.2-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:83b3fc8321303c9da62824730457ba2f7ae0970f0e2f7fc0117912df7f8a4826", size = 8644597, upload-time = "2026-10-06T04:25:23.451Z" }, + { url = "https://files.pythonhosted.org/packages/12/4d/e8cafd5fbe5f5fde043676838a4754e6ff4cd00323ecc81b3345eca6f185/onnx-1.23.2-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c03ecf6b835d136108eeaeeafbd0026fc7b3cf98661409fbc6b63d5a29361348", size = 8886609, upload-time = "2026-10-06T04:25:25.379Z" }, + { url = "https://files.pythonhosted.org/packages/de/56/cfc3ee63efc13dc112e29a79cfb77efecec50378fc4e2bd8f1b1ccd04fe8/onnx-1.23.2-cp311-cp311-win32.whl", hash = "sha256:a2b88d7e3634662f8d030117a7b02d864cfc965800547089ba62d3a9ceab3564", size = 7738192, upload-time = "2026-10-06T04:25:28.45Z" }, + { url = "https://files.pythonhosted.org/packages/81/0d/3aaf8f1fea3430282bd65acb3808d80fbdfeb90f20cfecb4072604e37ca6/onnx-1.23.2-cp311-cp311-win_amd64.whl", hash = "sha256:a40265d62b7a614041593e11370d316880f9628eb5a0d49d9028c9c0e7f1cc08", size = 7875390, upload-time = "2026-10-06T04:25:30.432Z" }, + { url = "https://files.pythonhosted.org/packages/ff/99/88c439dd84db6abc7d87e9d39584bdc29d4cbf5a1ae26015fcabf6679d36/onnx-1.23.2-cp311-cp311-win_arm64.whl", hash = "sha256:f8b9a5e25a390cc291600e5fd619f4b79708287a6bbc41a37209f364e08a63da", size = 8050663, upload-time = "2026-10-06T04:25:32.401Z" }, + { url = "https://files.pythonhosted.org/packages/d7/d9/967d6f6838ad60964de912a5e7d01915282899b254460705d952f5d14c1a/onnx-1.23.2-cp312-abi3-macosx_13_0_universal2.whl", hash = "sha256:1b8680ce1e6a9a4736374a9dce4de14ea8ee05e0dccf0784a78a6e5646bdc1f6", size = 9725612, upload-time = "2026-10-06T04:25:34.299Z" }, + { url = "https://files.pythonhosted.org/packages/f9/50/2e156ef2cae1c9f4ff01a41dffa43fc1eb7b969755055436bf6df1805d54/onnx-1.23.2-cp312-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a203efdbaabbbe8f25e854e2b2921382d6fcf4c67895656f939044b0632974e8", size = 8640515, upload-time = "2026-10-06T04:25:36.727Z" }, + { url = "https://files.pythonhosted.org/packages/87/56/21509a657f9a73ab0ca307d325043f49ca6c4ff6bf79edeb9e159190d44d/onnx-1.23.2-cp312-abi3-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7abf381d278f31ac62487fddedc9dd42da842dce94d5d43536836ee3efdf4a2b", size = 8881633, upload-time = "2026-10-06T04:25:38.868Z" }, + { url = "https://files.pythonhosted.org/packages/ec/ef/0a69093ffa0b999747b373c75d07182a812722a0e595d21f763a8d406260/onnx-1.23.2-cp312-abi3-pyemscripten_2026_0_wasm32.whl", hash = "sha256:e79e35e152d3095c6910ae81013bbc68679e32bfc0ca76f840968d4b6fdfb864", size = 7314844, upload-time = "2026-10-06T04:25:41.088Z" }, + { url = "https://files.pythonhosted.org/packages/97/a3/e4d4aedd0cc6820de416bb99623fc12b9a22a387d00596bb98505de9a805/onnx-1.23.2-cp312-abi3-win32.whl", hash = "sha256:b0b8dae0d33dd8606370bc264b0b1d6e64cfdf8b83d7c676fab8eff6b88ca409", size = 7736405, upload-time = "2026-10-06T04:25:42.893Z" }, + { url = "https://files.pythonhosted.org/packages/38/ce/102fd4a0b2a6d111a9c86745e084c4c68c0ee020eaa359a03a8d43e4646f/onnx-1.23.2-cp312-abi3-win_amd64.whl", hash = "sha256:9b382ba898a7c142a0801d03cf04ecabced96c1543c7b643a86f0928143802de", size = 7872489, upload-time = "2026-10-06T04:25:44.802Z" }, + { url = "https://files.pythonhosted.org/packages/bd/1d/37f2c7f821f79ceed3c976bd087d16abdd2b0bba6c19475322e7a31bae59/onnx-1.23.2-cp312-abi3-win_arm64.whl", hash = "sha256:80cef0fad59524d02c21ec93f4fbccdcc6223f1c33339d597519a2d27cac19a7", size = 8047076, upload-time = "2026-10-06T04:25:46.93Z" }, + { url = "https://files.pythonhosted.org/packages/5c/26/7a1319a7dd0556180525e573c674fc962ce37bd30dcb54ff9a8a43e8a26f/onnx-1.23.2-cp314-cp314t-macosx_13_0_universal2.whl", hash = "sha256:b2c07abb24f1c2c50ff5996c567eb9757470827f6d55b7f0af9d62c8e658bd7f", size = 9731174, upload-time = "2026-10-06T04:25:48.796Z" }, + { url = "https://files.pythonhosted.org/packages/ed/38/cbc9c5a72dbbc9d20f17e6855c643a2105053f756784cb167f69915c486d/onnx-1.23.2-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:32fd9c92244c2aea2b2c9e0e7b18fedcf6000434124ab6fc8796e22baa602d30", size = 8647447, upload-time = "2026-10-06T04:25:50.901Z" }, + { url = "https://files.pythonhosted.org/packages/2f/24/36c505c2f8079186ac7c2d858a7fda3c5591418ae92d134e2bf56f6eee1f/onnx-1.23.2-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:77674dc4fda2bde9a13aee67fb9ff658080159eb516d3a5b3fb2418d44dc70be", size = 8886676, upload-time = "2026-10-06T04:25:52.852Z" }, + { url = "https://files.pythonhosted.org/packages/db/1f/d30025c6ef40c0e42977c933aceba59ca2f5e3ab8b72673136f99c70268e/onnx-1.23.2-cp314-cp314t-win_amd64.whl", hash = "sha256:16ef247e51dbf42e32bd92f47ad772d17dda77f64c4017e0ded9725ff9ab3922", size = 7910684, upload-time = "2026-10-06T04:25:55.135Z" }, + { url = "https://files.pythonhosted.org/packages/69/84/7bbd40fc36f701968351b4f4c14de5bde61ba8f75b88f93b23d013f32f3d/onnx-1.23.2-cp314-cp314t-win_arm64.whl", hash = "sha256:1e6cbca3d808f811141ed0a0939e71b3a6c9fdefb2435f4a862ec776336718fe", size = 8089708, upload-time = "2026-10-06T04:25:56.893Z" }, +] + +[[package]] +name = "onnxruntime" +version = "1.32.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "flatbuffers" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "numpy", version = "2.5.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "packaging" }, + { name = "protobuf" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/5d/50be370b540a6cb9ea173503f5418e8315dfe5757400ad7720542d348b94/onnxruntime-1.32.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:366b9e53d07812cc5c92822cecf7563b76a8a0f32ba3bb8dd232a206ac3bcb6c", size = 22506162, upload-time = "2026-11-13T11:05:56.87Z" }, + { url = "https://files.pythonhosted.org/packages/b7/30/103820b32e9dc1d1fcfc5b519fd2de5bd699d25a25895caf5d726350d1b5/onnxruntime-1.32.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:2303372a85299b6757b0e11e1cbf13e410ddf7e10c37f4b37e99d1c90e7daf7c", size = 23195070, upload-time = "2026-11-13T11:06:00.34Z" }, + { url = "https://files.pythonhosted.org/packages/1d/46/e6f356c9539d2eed44126de3421a81e217da2ad91b22dc11b379cb1e384f/onnxruntime-1.32.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:5a34fc4dfeb5a7b4a74c95dcba1e773d722abda720b474edf1b0c419dc6d163d", size = 27773237, upload-time = "2026-11-13T11:06:03.754Z" }, + { url = "https://files.pythonhosted.org/packages/07/ff/c797464da311c580ec477077a5c65d7841599a46c35392b5978c0a5ae9a4/onnxruntime-1.32.0-cp311-cp311-win_amd64.whl", hash = "sha256:d7e0c45cc5f456ad7805e6dd256a7662736cda9c2fd17becae194eb3c2f6df72", size = 16695880, upload-time = "2026-11-13T11:06:06.877Z" }, + { url = "https://files.pythonhosted.org/packages/bd/ff/e14181a5315745007f06612d963c6f739b371452b089b5b8109c2379bd32/onnxruntime-1.32.0-cp311-cp311-win_arm64.whl", hash = "sha256:23361cdf98afac352d10aa7d9e0a10ceaeb02d38430fb693c6eff370196db62d", size = 16027290, upload-time = "2026-11-13T11:06:10.172Z" }, + { url = "https://files.pythonhosted.org/packages/6f/a4/480cd367bc135dd9951c89d461cc6af6be9302cd2ce91e231f6cb0e7ee1b/onnxruntime-1.32.0-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:d52510bbbcc880c13b826f7d75cdf33ac5cf0bb864d960000fc29ce73f0cb83e", size = 22519308, upload-time = "2026-11-13T11:06:13.395Z" }, + { url = "https://files.pythonhosted.org/packages/4a/8f/1e43fb994513c7c7a9c6965272ef89d963c1bd4080993a6267bf913701d1/onnxruntime-1.32.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:e36c187006e7a7c8b8d6d57f1a209dd63f52430dca6c282b177718ad6b841054", size = 23196724, upload-time = "2026-11-13T11:06:16.67Z" }, + { url = "https://files.pythonhosted.org/packages/a3/81/55845186c20cba59f614991f4065dea148e48eeb9749893768c85ce64327/onnxruntime-1.32.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:99e1074c4b2197accd5073052a465361be17b89c093b8ffb6e6bd8f986c52df8", size = 27780211, upload-time = "2026-11-13T11:06:19.734Z" }, + { url = "https://files.pythonhosted.org/packages/a9/3e/27039badc39a1b01628b6b40b1ff1bf4a886e6dfb2f311c483606b7c86f7/onnxruntime-1.32.0-cp312-cp312-win_amd64.whl", hash = "sha256:efe7456952c243a05a53d5b8732953625144642c2f3989094277f6217f0c0c40", size = 16698767, upload-time = "2026-11-13T11:06:22.618Z" }, + { url = "https://files.pythonhosted.org/packages/5d/e1/2ee4e15cebe7c2868e1d9ef391450db0951e6bbb2f01b2eb926722e19397/onnxruntime-1.32.0-cp312-cp312-win_arm64.whl", hash = "sha256:64d394c69d561af3efd4d4f49dcac8f11d0ce135a20701c16d53b74056cd4cf8", size = 16030610, upload-time = "2026-11-13T11:06:25.786Z" }, + { url = "https://files.pythonhosted.org/packages/f1/0c/97eb4ac42266545d7630e8231f8cc969f5c3f144d2ee6cb568ef45f81360/onnxruntime-1.32.0-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:27bf5dad46355a8a435c9c4e1556464d99ca834ea44e0f452909712068b8821b", size = 22518865, upload-time = "2026-11-13T11:06:28.89Z" }, + { url = "https://files.pythonhosted.org/packages/96/c7/26be6be3ebe42597a521645a7bb18701ce0716af87af0cd2c9281d2e84a5/onnxruntime-1.32.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:54d02baff2df38777b4c3cc7af326406fe8b8a48f54720f4c446d2d327920a79", size = 23195811, upload-time = "2026-11-13T11:06:31.896Z" }, + { url = "https://files.pythonhosted.org/packages/92/74/1f7c51522822e93aa91f633ebcd75688e2deebeca5901b2e6da8a8c5ad7c/onnxruntime-1.32.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:02ea12a28c069ea8510093d95a7f6ff8126bfd9fc5c0d3381c03b80fb2b424ba", size = 27780404, upload-time = "2026-11-13T11:06:36.602Z" }, + { url = "https://files.pythonhosted.org/packages/6f/ee/a776ccc71ba54de3739c20c7c815d9695c55db1d08e2b3c621452676c23f/onnxruntime-1.32.0-cp313-cp313-win_amd64.whl", hash = "sha256:c7f9aa98036ba2a47aa041a4a8c6d0a1f7bfe1bde44c131dcd15ce334f2f148d", size = 16697937, upload-time = "2026-11-13T11:06:39.92Z" }, + { url = "https://files.pythonhosted.org/packages/9b/08/9474c3f1a098da173cfd91047e1c6badaf0cfb4f5bd5598c54581a24c6d2/onnxruntime-1.32.0-cp313-cp313-win_arm64.whl", hash = "sha256:29e4b0fdd3bea834ace358bd8c48641266ec327f730363ab0ab5d0ca574d38fe", size = 16030922, upload-time = "2026-11-13T11:06:42.903Z" }, + { url = "https://files.pythonhosted.org/packages/08/3b/28be6dee643e29086c86b0b778e43d73e9c910aa044e8ac67856a9452131/onnxruntime-1.32.0-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:b01314ab8aa8176919818b19b899cd1cd72b5e4fc33e1127396f043206b6ceed", size = 23205671, upload-time = "2026-11-13T11:06:45.93Z" }, + { url = "https://files.pythonhosted.org/packages/4a/b0/8cc346bc2113c51d185d5f6ecbf8962c28ae2dfbc5461d9d36b79a267c6e/onnxruntime-1.32.0-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:926b6a87ffdcef56805b213807c28b97ae53763a630795baee1dfb420c2a5b68", size = 27797958, upload-time = "2026-11-13T11:06:48.981Z" }, + { url = "https://files.pythonhosted.org/packages/39/d7/2aaaf8e62912c222cbda5779ffacbea026e4953682680ca3eddd41075774/onnxruntime-1.32.0-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:ab327b736552324af8d2a38bef5a65ed773f67184a36ff642beec7f5b4e9b03f", size = 22520362, upload-time = "2026-11-13T11:06:52.067Z" }, + { url = "https://files.pythonhosted.org/packages/04/69/325c7e39e7000eadbbbfe39c07b42a3d2958a095cd46eeeb44cc235b2ed9/onnxruntime-1.32.0-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:4135431395c1f37de0811f452c20a8b774f51812fda6c49611ed9899bbdbeeb4", size = 23197888, upload-time = "2026-11-13T11:06:55.119Z" }, + { url = "https://files.pythonhosted.org/packages/94/b5/cd55e7f1dfcf2e5fbf3a6915a8c6b4cf81df091e81de2db40e58357ffba4/onnxruntime-1.32.0-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:48b878f9551d465aa79ee94ecaf49a1f6b5d27f2975efa775ded374db14d0af1", size = 27780528, upload-time = "2026-11-13T11:07:03.379Z" }, + { url = "https://files.pythonhosted.org/packages/da/50/bcc038601b4c044f07925ac11dc04e8ad4bbea87db9b4b3a2ac0823c6ddb/onnxruntime-1.32.0-cp314-cp314-win_amd64.whl", hash = "sha256:2b08ee990d00ab2ee129c5e039f7339963335a4d76f5bd22bfb4f896ae1cec0a", size = 17123630, upload-time = "2026-11-13T11:07:06.39Z" }, + { url = "https://files.pythonhosted.org/packages/67/12/c7a4ddc0e13e34ca16306b952ccc65be3fba1ef67eee96461c55bb3d155d/onnxruntime-1.32.0-cp314-cp314-win_arm64.whl", hash = "sha256:b33d822c19d036944bd969491d20095fc8def8ad0f32a969f6376df7568c0344", size = 16480674, upload-time = "2026-11-13T11:07:09.399Z" }, + { url = "https://files.pythonhosted.org/packages/f4/36/3a7a2333b88b7cb30b7b63185467f0476fd78e72ec33a51592edd3c3ead3/onnxruntime-1.32.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:2c4338c899144fd055a86c1d89424001db60e48a474e198c0fd0d1d577e4b663", size = 23204967, upload-time = "2026-11-13T11:07:12.639Z" }, + { url = "https://files.pythonhosted.org/packages/c2/db/80ef2ff511eb24c21eebea2649a4d2db611107fb35171bf4fd2515ae1070/onnxruntime-1.32.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:b224d11cfaecc95b85bdbd69f1673a984c7879af5823bb3ff377b9cb90b176fc", size = 27798510, upload-time = "2026-11-13T11:07:15.734Z" }, +] + +[[package]] +name = "onnxslim" +version = "0.1.99" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama" }, + { name = "ml-dtypes" }, + { name = "onnx" }, + { name = "packaging" }, + { name = "sympy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/fe/ac/8610e7274fe6bf26b6269f91de5a2acd03bfa2133153e691fc93f71a6f64/onnxslim-0.1.99.tar.gz", hash = "sha256:d662d6a6c384b64fe7464527a5865020c4335f8619a4a1272512ca0cc266867c", size = 616093, upload-time = "2026-11-04T03:13:12.228Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/76/d1/063874f0c02d3c00a169bce3ccf24a4f42ffbc4263d4b1593499c39f7a4c/onnxslim-0.1.99-py3-none-any.whl", hash = "sha256:6c6a3ddbbb7c5426f8f9c38ed1917bb4ab6335919c7d973328ba520faca469e4", size = 248552, upload-time = "2026-11-04T03:13:10.931Z" }, +] + [[package]] name = "opencv-python" version = "5.0.0.93" @@ -1258,6 +1414,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/76/c5/2fb8592d691bd114de25d9c84300b23541dca7060eac11d7b4bed0327786/polars_runtime_32-1.42.1-cp310-abi3-win_arm64.whl", hash = "sha256:7051226e6b42ffc395a7a9190377cd28649fbfb991b8f85c6271f4e1cfb736fb", size = 46718300, upload-time = "2026-06-30T04:56:59.855Z" }, ] +[[package]] +name = "protobuf" +version = "7.36.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d9/89/5b8517baa72f84a67b8a307ba953c91057af618bf40bf676f3c03551f8f0/protobuf-7.36.2.tar.gz", hash = "sha256:497d0463ff3316681da6c0b9e8d06cb465d61abce00b613ab42226175644d1bb", size = 512737, upload-time = "2026-09-17T20:07:59.326Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/72/98342feb672507c8f3a69e34b4fa8961f608edba5c1a48a6f47156d92cb5/protobuf-7.36.2-cp310-abi3-macosx_10_9_universal2.whl", hash = "sha256:cbc70b17ee27e28894c7fee8bb04be1abead49e936bc70eb60052531eee2079e", size = 456039, upload-time = "2026-09-17T20:07:51.542Z" }, + { url = "https://files.pythonhosted.org/packages/b6/ea/91fdf7c2b8bbd49cde056f00a9df6773532987e1c00fe2830b895af95c7e/protobuf-7.36.2-cp310-abi3-manylinux2014_aarch64.whl", hash = "sha256:e11e1f0180583a2af89db6a2ecd9e8dc40aa6d2988ca175bfd0e6d12ea72d74e", size = 344219, upload-time = "2026-09-17T20:07:52.914Z" }, + { url = "https://files.pythonhosted.org/packages/17/ab/5fd5f8ece73fad885c5a09aa849b32d70472f954ba3a92d3bb5974ea953b/protobuf-7.36.2-cp310-abi3-manylinux2014_s390x.whl", hash = "sha256:f4fee11ec330d238b34a05c9b675f693c20415d1c5bd7d5320cc2f8a798eb9cf", size = 357223, upload-time = "2026-09-17T20:07:53.985Z" }, + { url = "https://files.pythonhosted.org/packages/db/f3/3996583dd2906297a637af12114deddf7658af6e683fedb83be061983fb5/protobuf-7.36.2-cp310-abi3-manylinux2014_x86_64.whl", hash = "sha256:89f23aa53c24553a2416fd4fd1ec06f74fa42b14b546d8883128813f775bbfd2", size = 343223, upload-time = "2026-09-17T20:07:54.931Z" }, + { url = "https://files.pythonhosted.org/packages/fc/1b/dcc64f358fcb51811b58ae40b3d28f820725f116d86487cc20bd4b130701/protobuf-7.36.2-cp310-abi3-win32.whl", hash = "sha256:912c1221170e16c08d1f086762f563dd61ff83c18b5fa6652952dfaded66f728", size = 442998, upload-time = "2026-09-17T20:07:55.826Z" }, + { url = "https://files.pythonhosted.org/packages/8a/55/b77bda4e5e5f5971fb51b07663694690e9afdb9402136c16a522bd621cad/protobuf-7.36.2-cp310-abi3-win_amd64.whl", hash = "sha256:a300819d441e078a5608c0d3c709796bb548136058fda017ae51d425b44fd353", size = 456514, upload-time = "2026-09-17T20:07:57.188Z" }, + { url = "https://files.pythonhosted.org/packages/e4/04/d52c7016b04b6c5108f26691f9d33ec82a9b65d041f1a9c771137693d618/protobuf-7.36.2-py3-none-any.whl", hash = "sha256:bdb3a345d48db958e6ce1f18e508beb0cc981d64f24088427549c866cd039f1e", size = 179806, upload-time = "2026-09-17T20:07:58.211Z" }, +] + [[package]] name = "psutil" version = "7.2.2" @@ -1507,8 +1678,12 @@ name = "scipy" version = "1.18.1" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version >= '3.12' and sys_platform == 'win32'", - "python_full_version >= '3.12' and sys_platform != 'win32'", + "python_full_version >= '3.14' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.12.*' and sys_platform == 'win32'", + "python_full_version >= '3.14' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'win32'", + "python_full_version == '3.12.*' and sys_platform != 'win32'", ] dependencies = [ { name = "numpy", version = "2.5.0", source = { registry = "https://pypi.org/simple" } },