diff --git a/agent_docs/ml-pipeline.md b/agent_docs/ml-pipeline.md index ca11442..5b163ad 100644 --- a/agent_docs/ml-pipeline.md +++ b/agent_docs/ml-pipeline.md @@ -83,15 +83,22 @@ Current phase: `ml/experiments/current_phase.txt` - **Detection:** per-class and per-domain precision / recall / F1 / accuracy with Wilson 95% CIs, confusion matrix, small-object (junction) recall, at one operating confidence (default 0.35). "accuracy" = TP / GT instances of the class (the phase-gate number). Domains come from the image file name prefix (`syn_` synthetic, `rf_` roboflow_real, `cghd_` cghd_real, `dss_` digisim_screenshot; add more with `--domain-rule PREFIX=name`). + When the dataset root has a `generate_v2` `manifest.json`, test images flagged `held_out_style` are reported as their own domain + `_heldout_style` (for the synthetic test add `--domain-rule 0=synthetic`, since generator file names have no prefix). Classes with fewer than 30 GT instances are labelled `low n` instead of judged. Models are scored in the dataset's vocabulary: predictions map by class name, then by legacy alias (`ml/classes.yaml`); predictions with no counterpart are counted as `unmapped`. +- **Ignore regions:** when the split has a sibling `ignore/` folder (T4 real data), an unmatched prediction with at least half its area inside an + `uncertain_fet`, `uncertain_supply` or `uncertain_terminal` box is not counted as a false positive (objects T4 could not label); + `unmapped` regions stay scored. `--ignore-reason none` disables it; the report states how many predictions were masked. - **Legacy block:** the original ultralytics validation numbers (mAP, max-F1 per class, confusion-matrix accuracy); `--reproduce OLD_eval_test.json` checks them. - **End-to-end (optional):** `--gt-netlists DIR --pred-netlists DIR` (files `.json`, schema in `ml/eval_netlist.py`; the T2 generator's pin-map netlists are read as ground truth directly, and the stage 4 exporter output is a valid prediction) gives net precision/recall/F1 over pin pairs (MOSFET bulk pins unscored), netlist exact-match rate, and truth-table equivalence of the rebuilt circuit under DigiSim's own `simulate()` (`ml/sim_bridge/truth_table.cjs`; needs `cd frontend && npm install`; `--no-truth-table` skips it). -- **Frozen sets:** the SHA-256 of the split's images and labels directories as resolved from `data.yaml`, its netlists directory (`--gt-netlists` when given) and class names must equal the entry in `ml/frozen_sets.json`, otherwise the run exits 3 and writes nothing. +- **Frozen sets:** the SHA-256 of the split's images and labels directories as resolved from `data.yaml`, its netlists directory (`--gt-netlists` when given), its `ignore/` regions (when present) and class names must equal the entry in `ml/frozen_sets.json`, otherwise the run exits 3 and writes nothing. Register a new set once with `--freeze --frozen-name NAME --freeze-note "..."`; tooling never overwrites an entry. `--freeze` exists because the hash check needs a recorded hash to compare against, and every later dataset task (T4 onwards) registers its frozen entry this way. A split with no registered set runs unchecked and the report says "(not frozen - unverified)". + Registered: `gate12_test`, `real_t4_test` (T4 real test: CGHD drafter 20 + 3 Roboflow images, `ml/data_real/yolo`), `synth_v2_seed1_n8000_test` + (`generate_v2.py --count 8000 --seed 1` test split). - **Baselines:** `ml/baselines/gate12.json` is the old 12-class model on the gate-era test split (`gate12_test`); compare a new run with `--baseline ml/baselines/gate12.json`. ## Dataset @@ -100,8 +107,8 @@ Current phase: `ml/experiments/current_phase.txt` topology-hash splits, held-out test styles; see `docs/synth_v2/README.md`); legacy gate-era `backend/data_gen/screenshot_pipeline.py` - **Augmentation:** `backend/data_gen/augmentation.py` - **Minimum size:** Phase 1 → 500 images. Phase 2+ → 2000 images -- **Format:** YOLO `.txt` per image — ` ` (normalized) -- **Class balance:** no class under 10% — check before every training run +- **Format:** YOLO `.txt` per image - ` ` (normalized) +- **Class balance:** no class under 10% - check before every training run ### Real data and the frozen eval set (`ml/real_data/`) Fetched and converted data live in `ml/data_real/` (gitignored); committed: scripts, `ml/data_manifest.json` (SHA-256 of every @@ -118,11 +125,99 @@ labels in `ml/real_data/labels/`. ## Training Harness `ml/train.py` runs on CPU, one GPU or DDP with the same command (`--device cpu | auto | 0 | 0,1,2,3`); `--workers` defaults to the usable CPU count (max 8) and `--batch` is the total across GPUs (default: 16 per device). Presets: `smoke` (2 epochs, yolov8n, imgsz 320), `stage-a` (synthetic pretrain, yolov8s, imgsz 960, 100 epochs), `stage-b` (mixed fine-tune from the stage-A `best.pt` via `--model`, real images repeated `--real-oversample` times through `--real-train DIR`, lr0 0.002). +`--time HOURS` (both trainers) replaces the epoch count with a wall-clock budget; ultralytics fits the epochs and LR schedule to it. Always pretrained weights; `--resume RUN_DIR` continues an interrupted run (it keeps the run's base model, total batch and rebuilt mixed/oversampled dataset, and `metrics.json` records `resumed_from`); `--dry-run` prints the resolved plan (device layout, batch per process, dataset counts, class-vocabulary check against `ml/classes.yaml`) without importing torch. Each run folder (`ml/experiments/run_*`, gitignored) holds `config.yaml`, `notes.md`, `best.pt`, `best.onnx` and `metrics.json` (per-class P/R/F1/AP/accuracy, the F1/accuracy gate verdict, environment, dataset counts and the effective `data_effective` yaml). `ml/kaggle/train_kaggle.py` is the self-contained Kaggle twin (installs ultralytics, finds `data.yaml` under `/kaggle/input`, writes the same artifacts to `/kaggle/working/digisim_run`); `ml/tests/test_train_harness.py` keeps its preset table equal to `train.py`. +`ml/kaggle/build_dataset.py --synth DIR --out OUT` assembles the stage-A/B dataset folder (synthetic + real tier A labels, real images downsized, `uncertain_*` regions painted out of real train/valid, `stage_a.yaml`, `stage_b.yaml`, the trainer and `t7_session.py`); upload it as one private Kaggle dataset and run `t7_session.py` (stage A then stage B, each time-budgeted) as the kernel. `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). +## T7 Results (2026-11-18): phase 2 gate NOT met + +Tier A detector trained transistor-first: stage A on synthetic data only, stage B mixed with the T4 real data. +**The synthetic gate is missed on two classes (VDD, XOR), and every real-data gate is missed.** Phase 2 is not reached; +`ml/experiments/current_phase.txt` is unchanged. All numbers come from the T6 harness (`evaluate.py`, conf 0.35, IoU 0.5, Wilson 95% CIs) +on the frozen sets `synth_v2_seed1_n8000_test` and `real_t4_test` (hash-verified, never used for tuning or model selection). + +**Synthetic held-out-style test** (`synthetic_heldout_style` domain: 391 of the 812 test images, styles never seen in training). +The cells show F1 / accuracy; the gate is F1 >= 0.95 and accuracy >= 0.95. + +| run | NMOS | PMOS | VDD | GND | IN | OUT | JUNC | AND | OR | NOT | NAND | NOR | XOR | XNOR | failing | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| GPU stage A (synthetic only) | .976/.996 | .979/.969 | **.770/.653** | .998/.998 | .998/.998 | .997/1.0 | .976/.999 | .983/.967 | .982/1.0 | .987/.974 | .967/1.0 | .990/1.0 | **.941/.923** | .964/.985 | VDD, XOR | +| GPU stage B (mixed) | .972/.996 | .975/.966 | **.734/.669** | .992/1.0 | 1.0/1.0 | 1.0/1.0 | .971/.999 | .984/.984 | .991/1.0 | 1.0/1.0 | .989/1.0 | .981/1.0 | .961/**.942** | .964/.971 | VDD, XOR | +| CPU nano stage A | .878/.954 | .871/.854 | .395/.257 | .941/.930 | .913/.868 | .718/.604 | .937/.994 | .816/.836 | .769/.818 | .920/.885 | .748/.909 | .817/.922 | .684/.769 | .818/.794 | 13 of 14 | + +On the seen-style half of the test split, both GPU models reach F1 >= 0.98 and accuracy >= 0.98 for every class. + +**Real held-out test** (`real_t4_test`: 99 images, CGHD drafter 20 plus 3 Roboflow images). The cells show F1 [95% CI]; the gate is F1 >= 0.85 for classes with >= 30 test instances, and JUNCTION recall >= 0.90. +The table covers tier A only; the harness `overall` row also counts the 1614 tier B objects (resistors, capacitors, inductors) as misses. + +| class (test n) | GPU stage A (synthetic only) | GPU stage B (mixed) | CPU nano stage A | +|---|---|---|---| +| NMOS (116) | 0.000 | 0.601 [0.53, 0.67] | 0.009 | +| PMOS (78) | 0.000 | 0.564 [0.47, 0.65] | 0.009 | +| VDD (140) | 0.000 | 0.215 [0.17, 0.28] | 0.012 | +| GND (551) | 0.119 | 0.630 [0.60, 0.66] | 0.114 | +| INPUT_PORT (52) | 0.000 | 0.147 [0.08, 0.25] | 0.000 | +| JUNCTION (5124) | 0.187 | 0.758 [0.75, 0.77] | 0.347 | +| AND (101) | 0.188 | 0.507 [0.43, 0.59] | 0.113 | +| OR (35) | 0.301 | 0.436 [0.31, 0.57] | 0.186 | +| **JUNCTION recall** | 0.154 [0.14, 0.16] | **0.729 [0.72, 0.74]** | 0.260 [0.25, 0.27] | +| tier A micro P / R / F1 | 0.190 / 0.143 / 0.163 | 0.786 / 0.668 / 0.722 | 0.354 / 0.225 / 0.275 | + +Too few real test instances to judge (reported, not gated; the synthetic score is the only evidence for these classes): +OUTPUT_PORT 28, NOT 10, NAND 1, NOR 1, XOR 1, XNOR 0. +The ignore regions masked 92 unmatched stage-B predictions (690 `uncertain_*` regions); `unmapped` regions stayed scored. + +**Synthetic-only vs mixed ablation.** On real images, stage A to stage B raises tier A F1 from 0.16 to 0.72 and JUNCTION recall from 0.15 to 0.73. +On the synthetic held-out styles it costs almost nothing (micro F1 0.973 vs 0.968). Synthetic data alone does not transfer to hand-drawn photos. +Each real class gains 0.3 to 0.6 F1, but none comes near 0.85. + +**Run configuration.** + +| run | where | model | data | imgsz | budget | result | +|---|---|---|---|---|---|---| +| GPU stage A | Kaggle 2x T4 DDP, [digisim-t7-run-a](https://www.kaggle.com/code/manijos/digisim-t7-run-a) (private) | yolov8s from COCO | 6354 synthetic train / 834 valid | 960 | `--time 2.8` | 97 epochs, 2.9 h, batch 32, SGD lr0 0.01 | +| GPU stage B | same session | stage A `best.pt` | 2500 synthetic + 231 real x4 = 3424 train; valid 834 synthetic + 100 real | 960 | `--time 1.8` | early-stopped at epoch 33 (patience 15), best epoch 18, 0.6 h | +| CPU nano stage A | local CPU, 4 threads | yolov8n warm-started from the old 12-class gate weights | 6354 synthetic | 640 | `--time 2.5` | 5 epochs, 2.1 h (CPU fallback only, not a candidate) | + +Data: `generate_v2.py --count 8000 --seed 1`, plus T4 real data (CGHD drafters 19 and 25 for train, 16 for valid, 20 for test, and Roboflow). +Both were assembled by `ml/kaggle/build_dataset.py`: tier A labels only, real images capped at 1920 px, `uncertain_*` regions painted out of real train/valid. +The kernel ran `ml/kaggle/t7_session.py` (ultralytics 8.4.215, torch 2.11 cu130). Local evaluation used ultralytics 8.4.86 and torch 2.12.1 on CPU. + +**Artifacts** (outside git, under `/home/mani/linux-fleet-home/data/digisim-t7-train/`; weights are never committed). sha256 values: + +| file | sha256 | +|---|---| +| `kaggle_out/run_a/stage_a/best.pt` | `6cee6e0c3871a51f1163138838eb4b42cdcb574694256e4c5bcd803688a909d2` | +| `kaggle_out/run_a/stage_b/best.pt` | `79b3690b78b57112e694fab09bcfdaf817c5e6edb392d518f97ee72da10154b9` | +| `kaggle_out/run_a/stage_b/best.onnx` | `d8a48245ad3d71c66e149e3e9bf5529267ece82e0a4dda376d902630012ea43d` | +| `ml/experiments/t7_cpu_nano_stage_a/best.pt` | `402b29dd0fb6dff31450c66b83fd039cfb607046f89c2e424039514a6e5271c5` | +| trainer `metrics.json` stage A / B / nano | `635f36bd...f414` / `9a1c8857...828a` / `6698b8f1...d508` | +| `eval/gpu_stage_b_real.json` / `eval/gpu_stage_b_synth.json` | `7a2ba5c18cb3a243...3e4d` / `8a3c83bca38dff69...0657` | +| `eval/gpu_stage_a_real.json` / `eval/gpu_stage_a_synth.json` | `549a0427e3588ed4...aced` / `adbe1447eaef13ea...4036` | +| `eval/cpu_nano_a_real.json` / `eval/cpu_nano_a_synth.json` | `4108fe933e5c94be...2d2f` / `1332af23391fe718...9cf1` | + +**Why the gates are missed, and what data would fix it.** The architecture is not the bottleneck: the same model reaches about 0.99 on seen synthetic styles. +- **Real data volume and drafter diversity.** Training saw 231 real images from 2 drafters, and the test set is a third drafter. Recall is the failure mode: precision is 0.79 to 0.92 for NMOS, PMOS, GND and JUNCTION, but recall is 0.42 to 0.73. + Fix: label tier A on more CGHD drafters. The T4 pilot used only 4 (`CGHD_PILOT_SPLITS` in `ml/real_data/config.py`). Target at least 1000 real training images from at least 10 drafters, keeping the drafter split; adding drafters to the test split creates a new frozen set. + VDD (F1 0.22) and INPUT_PORT (0.15) are the worst, although train has 184 VDD and 207 INPUT_PORT instances. My best read is drafter style: each drafter draws supplies and terminals their own way, so 2 training drafters do not cover drafter 20. + In addition, 907 `uncertain_terminal` regions were painted out of the real train images. Resolving those labels (`ml/real_data/labels/`) turns them into positives instead of erased marks. +- **Model selection on the wrong signal.** Stage B early-stopped, and picked `best.pt`, on a validation set that is 90% synthetic (834 of 934 images). + Synthetic fitness was saturated, so selection was close to noise for real-image quality (best epoch 18; stopped at epoch 33, about 1.2 h before the 1.8 h budget ran out). + Fix (data/config, not architecture): validate stage B on real images only (drafter 16), or weight real images in the fitness. + Disable early stopping for the short fine-tune. This needs no new data and is the cheapest next run. It changes selection only, so the real test set stays untouched. +- **Small junctions.** CGHD junctions are about 1% of the image width (about 10 px at 960). Small-object recall is 0.65. Fix: train and evaluate real images at 1280, or tile them. + This sits ahead of more data for JUNCTION recall. +- **Synthetic VDD and XOR on held-out styles.** The held-out styles include a `circle` VDD symbol and `sketch` strokes that training never shows, by design. The two misses mean the model learned the specific VDD glyphs, not the concept. + Fix: more VDD symbol variants and line styles in the generator's training styles (keep the held-out ones held out). For XOR, more sketch-like double-curve gates. + +**Follow-ups (not done here).** +- `optimizer=auto` in ultralytics ignores `lr0`: stage A ran SGD at 0.01, and stage B AdamW at an auto-computed learning rate. Pin `optimizer` in the presets. +- The `generate_v2` manifest hash for seed 1 / 8000 differs from the one in `docs/synth_v2/README.md`. Re-check generator determinism across environments. +- T10 needs a weights distribution path. The stage B weights (`79b3690b...`) are the best tier A model so far, but they do not pass the gate. + ## Key Principle Dataset quality > annotation correctness > pipeline correctness > model architecture. Fix data before changing models. diff --git a/ml/eval_frozen.py b/ml/eval_frozen.py index d56e675..b31c738 100644 --- a/ml/eval_frozen.py +++ b/ml/eval_frozen.py @@ -52,7 +52,7 @@ def file_sha256(path: Path) -> str: return digest.hexdigest() -def hash_split(images_dir: Path, labels_dir: Path, netlists_dir: Path, class_names: Sequence[str]) -> SplitDigest: +def hash_split(images_dir: Path, labels_dir: Path, netlists_dir: Path, class_names: Sequence[str], ignore_dir: Path | None = None) -> SplitDigest: """ Deterministic digest of a dataset split, over exactly the directories an evaluation reads. @@ -61,8 +61,10 @@ def hash_split(images_dir: Path, labels_dir: Path, netlists_dir: Path, class_nam labels_dir: Directory holding the split's YOLO label files. netlists_dir: Directory holding the split's ground-truth netlists (may not exist). class_names: Class names in id order (label ids are meaningless without them). + ignore_dir: Directory of per-image ignore-region JSON files the evaluation masks with (may be None or + missing; a split without one hashes exactly as before ignore regions existed). Returns: - The SplitDigest. Only *.txt labels, image files and *.json netlists count; caches are ignored. + The SplitDigest. Only *.txt labels, image files and *.json netlists / ignore regions count; caches are ignored. Raises: FileNotFoundError: If the image or label directory does not exist. """ @@ -75,13 +77,14 @@ def hash_split(images_dir: Path, labels_dir: Path, netlists_dir: Path, class_nam ("images", images_dir, lambda p: p.suffix.lower() in IMAGE_SUFFIXES), ("labels", labels_dir, lambda p: p.suffix == ".txt"), ("netlists", netlists_dir, lambda p: p.suffix == ".json"), + ("ignore", ignore_dir, lambda p: p.suffix == ".json"), ): - if not folder.is_dir(): + if folder is None or not folder.is_dir(): continue for path in sorted(folder.iterdir()): if path.is_file() and keep(path): entries.append((f"{kind}/{path.name}", file_sha256(path))) - counts[kind] += 1 + counts[kind] = counts.get(kind, 0) + 1 digest = hashlib.sha256() digest.update(("classes\t" + json.dumps(list(class_names)) + "\n").encode()) for rel, file_hash in sorted(entries): diff --git a/ml/eval_metrics.py b/ml/eval_metrics.py index 8e988d8..5f3006a 100644 --- a/ml/eval_metrics.py +++ b/ml/eval_metrics.py @@ -171,6 +171,42 @@ def match_boxes(gt: np.ndarray, pred: np.ndarray, iou_threshold: float = IOU_MAT return pairs +IGNORE_IOA_THRESHOLD = 0.5 + + +def drop_ignored(gt: np.ndarray, pred: np.ndarray, ignore: np.ndarray, iou_threshold: float = IOU_MATCH_THRESHOLD, ioa_threshold: float = IGNORE_IOA_THRESHOLD) -> tuple[np.ndarray, int]: + """ + Remove unmatched predictions that fall inside "don't care" regions (COCO-crowd style masking). + + A prediction is dropped only when it matches no ground-truth box and at least `ioa_threshold` of its + area lies inside one ignore box, so a correct detection of an object we could not label (for example a + transistor of undecided polarity) is not counted as a false positive, while every real error still counts. + + Args: + gt: (n, 5) rows [cls, x1, y1, x2, y2]. + pred: (m, 6) rows [cls, conf, x1, y1, x2, y2]. + ignore: (k, 4) xyxy ignore boxes in pixels. + iou_threshold: IoU used to decide that a prediction matches a ground-truth box. + ioa_threshold: Minimum fraction of the prediction's area inside an ignore box. + Returns: + (the kept predictions, number of dropped predictions). + """ + if len(pred) == 0 or len(ignore) == 0: + return pred, 0 + matched = {p for _, p in match_boxes(gt, pred, iou_threshold)} + boxes = pred[:, 2:6].astype(np.float64) + ign = ignore.astype(np.float64) + ix1 = np.maximum(boxes[:, None, 0], ign[None, :, 0]) + iy1 = np.maximum(boxes[:, None, 1], ign[None, :, 1]) + ix2 = np.minimum(boxes[:, None, 2], ign[None, :, 2]) + iy2 = np.minimum(boxes[:, None, 3], ign[None, :, 3]) + inter = np.clip(ix2 - ix1, 0, None) * np.clip(iy2 - iy1, 0, None) + area = np.clip((boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]), 1e-9, None) + inside = (inter / area[:, None]).max(axis=1) >= ioa_threshold + drop = np.array([inside[i] and i not in matched for i in range(len(pred))], dtype=bool) + return pred[~drop], int(drop.sum()) + + @dataclass class DetectionAccumulator: """Accumulates the confusion matrix and small-object counters over many images.""" diff --git a/ml/eval_report.py b/ml/eval_report.py index 3a196ae..db6fdcd 100644 --- a/ml/eval_report.py +++ b/ml/eval_report.py @@ -192,6 +192,21 @@ def _e2e_rows(label: str, rec: JsonDict) -> list[str]: ] +def _ignore_lines(masking: JsonDict | None) -> list[str]: + """ + One Markdown line describing ignore-region masking, or nothing when no regions were used. + + Args: + masking: The detection block's ignore_masking record (reasons, regions, dropped_predictions), or None. + Returns: + Zero or one lines. + """ + if not masking or not masking.get("reasons"): + return [] + reasons = ", ".join(masking["reasons"]) + return [f"Ignore regions ({reasons}): {masking['regions']} regions, {masking['dropped_predictions']} unmatched predictions inside them not counted."] + + def render_markdown(report: JsonDict, baseline: JsonDict | None = None) -> str: """ Render a whole evaluation report as Markdown. @@ -235,6 +250,7 @@ def render_markdown(report: JsonDict, baseline: JsonDict | None = None) -> str: lines += [ "", f"Operating point: conf >= {det['conf']}, IoU >= {det['iou_threshold']}.", + *_ignore_lines(det.get("ignore_masking")), f"Verdicts: F1 >= {F1_GATE} and accuracy >= {ACC_GATE} (synthetic / overall), F1 >= {REAL_F1_GATE} (real domains); `low n` = fewer than 30 GT instances.", "", ] diff --git a/ml/evaluate.py b/ml/evaluate.py index c95e877..24c787e 100644 --- a/ml/evaluate.py +++ b/ml/evaluate.py @@ -42,6 +42,7 @@ IOU_MATCH_THRESHOLD, DetectionAccumulator, domain_for, + drop_ignored, parse_domain_rule, ) from eval_netlist import evaluate_netlists @@ -60,6 +61,12 @@ DEFAULT_OPERATING_CONF = 0.35 # production DETECTION_CONFIDENCE_THRESHOLD (backend/pipeline/detector.py) DEFAULT_TOLERANCE = 0.02 OMP_THREADS = "4" +# Ignore-region reasons (ml/data_real/yolo/ignore//.json, written by real_data.build) masked by default: +# objects we could not label (undecided polarity, terminal role or supply). Unmapped classes stay scored, so a +# tier A prediction on, say, an op-amp still counts as a false positive. +DEFAULT_IGNORE_REASONS = ("uncertain_fet", "uncertain_supply", "uncertain_terminal") +# Domain suffix for synthetic test images the generator rendered in held-out styles (manifest.json held_out_style). +HELD_OUT_STYLE_SUFFIX = "_heldout_style" EXIT_FROZEN = 3 EXIT_REPRODUCTION = 4 @@ -109,6 +116,24 @@ def load_dataset_info(data: Path, split: str) -> DatasetInfo: return DatasetInfo(root=root, names=names, images_dir=images_dir, labels_dir=sibling_dir(images_dir, "labels"), netlists_dir=sibling_dir(images_dir, "netlists")) +def held_out_style_images(root: Path) -> frozenset[str]: + """ + Image file names the synthetic generator flagged as held-out styles (generate_v2 manifest.json at the dataset root). + + Args: + root: Dataset root (holds manifest.json for generate_v2 output). + Returns: + The flagged image file names; empty when the dataset has no generator manifest. + """ + manifest = root / "manifest.json" + if not manifest.is_file(): + return frozenset() + samples = json.loads(manifest.read_text()).get("samples") + if not isinstance(samples, list): + return frozenset() + return frozenset(Path(s["files"]["image"]["path"]).name for s in samples if s.get("held_out_style")) + + def sibling_dir(images_dir: Path, name: str) -> Path: """ The directory beside a split's images, found the way ultralytics finds labels: the last 'images' path component is swapped. @@ -160,6 +185,29 @@ def read_labels(label_file: Path, width: int, height: int) -> np.ndarray: return np.asarray(rows, dtype=np.float64).reshape(-1, 5) +def read_ignore(ignore_file: Path, reasons: tuple[str, ...]) -> np.ndarray: + """ + Read one image's ignore regions (pixel xyxy) whose reason is in `reasons`. + + Args: + ignore_file: JSON list of {"reason", "xyxy", ...} records; may not exist. + reasons: Reasons to keep (empty keeps none). + Returns: + (k, 4) float array of xyxy boxes in pixels (empty when the file is missing or nothing matches). + Raises: + ValueError: If the file is not a list of records with a 4-number xyxy. + """ + if not reasons or not ignore_file.exists(): + return np.zeros((0, 4), dtype=np.float64) + records = json.loads(ignore_file.read_text()) + if not isinstance(records, list): + raise ValueError(f"{ignore_file}: expected a JSON list") + boxes = [r["xyxy"] for r in records if isinstance(r, dict) and r.get("reason") in reasons] + if any(len(b) != 4 for b in boxes): + raise ValueError(f"{ignore_file}: every xyxy needs 4 numbers") + return np.asarray(boxes, dtype=np.float64).reshape(-1, 4) + + def build_class_map(model_names: dict[int, str], dataset_names: tuple[str, ...], aliases: dict[str, str]) -> list[int]: """ Map each model class id to a dataset class id by name, then by legacy alias. @@ -185,6 +233,9 @@ def predict_split(weights: Path, image_paths: list[Path], imgsz: int, device: st """ Run the detector once over a list of images at a very low confidence floor. + Images are predicted one at a time: given a list source, ultralytics decodes every image into memory before + the first prediction, which runs out of RAM on a split of several hundred images. + Args: weights: Trained .pt weights. image_paths: Images to run. @@ -201,7 +252,8 @@ def predict_split(weights: Path, image_paths: list[Path], imgsz: int, device: st raise FileNotFoundError(f"Weights not found: {weights} - train first") model = YOLO(str(weights)) out: dict[str, tuple[np.ndarray, tuple[int, int]]] = {} - for path, result in zip(image_paths, model.predict(source=[str(p) for p in image_paths], imgsz=imgsz, conf=PREDICT_CONF_FLOOR, device=device, stream=True, verbose=False), strict=True): + for path in image_paths: + result = model.predict(source=str(path), imgsz=imgsz, conf=PREDICT_CONF_FLOOR, device=device, verbose=False)[0] boxes = result.boxes xyxy = boxes.xyxy.cpu().numpy() conf = boxes.conf.cpu().numpy() @@ -220,6 +272,7 @@ def evaluate_detection( small_px: float, device: str, domain_rules: tuple[tuple[str, str], ...], + ignore_reasons: tuple[str, ...] = DEFAULT_IGNORE_REASONS, ) -> dict[str, Any]: """ Per-class and per-domain detection metrics at one operating confidence. @@ -232,9 +285,11 @@ def evaluate_detection( iou: IoU threshold for prediction-to-GT matching. small_px: Longest-side threshold (pixels) for the small-object recall. device: Torch device string. - domain_rules: (filename prefix, domain) rules. + domain_rules: (filename prefix, domain) rules; images flagged held_out_style in the dataset manifest get the + domain plus "_heldout_style". + ignore_reasons: Ignore-region reasons to mask (read from the split's sibling `ignore` directory when it exists). Returns: - Dict with overall, per_class, per_domain, confusion_matrix, junction_recall and operating-point settings. + Dict with overall, per_class, per_domain, confusion_matrix, junction_recall, ignore-masking counts and operating-point settings. Raises: FileNotFoundError: If the weights are missing or the split holds no images. """ @@ -246,6 +301,11 @@ def evaluate_detection( n = len(info.names) overall = DetectionAccumulator(n, small_px, iou) per_domain: dict[str, DetectionAccumulator] = {} + held_out = held_out_style_images(info.root) + ignore_dir = sibling_dir(info.images_dir, "ignore") + use_ignore = bool(ignore_reasons) and ignore_dir.is_dir() + ignore_regions = 0 + ignored_predictions = 0 for path in images: preds, (height, width) = predictions[path.name] preds = preds[preds[:, 1] >= conf] if len(preds) else preds @@ -253,8 +313,14 @@ def evaluate_detection( preds = preds.copy() preds[:, 0] = class_map[preds[:, 0].astype(int)] gt = read_labels(info.labels_dir / f"{path.stem}.txt", width, height) + if use_ignore: + ignore = read_ignore(ignore_dir / f"{path.stem}.json", ignore_reasons) + ignore_regions += len(ignore) + preds, dropped = drop_ignored(gt, preds if len(preds) else np.zeros((0, 6)), ignore, iou) + ignored_predictions += dropped overall.add_image(gt, preds) - per_domain.setdefault(domain_for(path.name, domain_rules), DetectionAccumulator(n, small_px, iou)).add_image(gt, preds) + domain = domain_for(path.name, domain_rules) + (HELD_OUT_STYLE_SUFFIX if path.name in held_out else "") + per_domain.setdefault(domain, DetectionAccumulator(n, small_px, iou)).add_image(gt, preds) per_class = overall.per_class(info.names) return { "conf": conf, @@ -266,6 +332,7 @@ def evaluate_detection( "per_domain": {d: {"overall": acc.overall(), "per_class": acc.per_class(info.names)} for d, acc in sorted(per_domain.items())}, "confusion_matrix": overall.confusion(info.names), "junction_recall": per_class["JUNCTION"]["recall"] if "JUNCTION" in per_class else None, + "ignore_masking": {"reasons": list(ignore_reasons) if use_ignore else [], "regions": ignore_regions, "dropped_predictions": ignored_predictions}, } @@ -428,6 +495,12 @@ def build_parser() -> argparse.ArgumentParser: p.add_argument("--iou", type=float, default=IOU_MATCH_THRESHOLD) p.add_argument("--small-px", type=float, default=DEFAULT_SMALL_PX, help="GT boxes with longest side <= this are 'small objects'") p.add_argument("--device", default="cpu") + p.add_argument( + "--ignore-reason", + action="append", + default=None, + help=f"ignore-region reason to mask (repeatable; default {', '.join(DEFAULT_IGNORE_REASONS)}; 'none' disables masking)", + ) p.add_argument("--domain-rule", action="append", default=[], metavar="PREFIX=NAME", help="Extra filename-prefix domain rule (repeatable)") p.add_argument("--skip-legacy", action="store_true", help="Skip the ultralytics validation block") p.add_argument("--gt-netlists", type=Path, help="Directory of ground-truth netlists (.json)") @@ -463,7 +536,7 @@ def main(argv: list[str] | None = None) -> int: parser.error("--gt-netlists and --pred-netlists go together") info = load_dataset_info(args.data, args.split) - digest: SplitDigest = hash_split(info.images_dir, info.labels_dir, args.gt_netlists or info.netlists_dir, info.names) + digest: SplitDigest = hash_split(info.images_dir, info.labels_dir, args.gt_netlists or info.netlists_dir, info.names, sibling_dir(info.images_dir, "ignore")) if not args.freeze and not args.frozen_name: args.frozen_name = infer_frozen_name(args.split, info.names, args.registry) if args.split == "test" and not args.frozen_name: @@ -505,7 +578,8 @@ def main(argv: list[str] | None = None) -> int: }, } status = 0 - report["detection"] = evaluate_detection(info, args.weights, args.imgsz, args.conf, args.iou, args.small_px, args.device, rules) + reasons = tuple(r for r in (args.ignore_reason or DEFAULT_IGNORE_REASONS) if r != "none") + report["detection"] = evaluate_detection(info, args.weights, args.imgsz, args.conf, args.iou, args.small_px, args.device, rules, reasons) if not args.skip_legacy: report["legacy"] = evaluate(args.weights, args.data, args.split, args.imgsz, args.out_dir / "ultralytics_val", args.device) print_report(report["legacy"]) diff --git a/ml/frozen_sets.json b/ml/frozen_sets.json index c25d88b..7756cb4 100644 --- a/ml/frozen_sets.json +++ b/ml/frozen_sets.json @@ -20,5 +20,59 @@ "note": "Legacy 12-class gate-era test split (75 synthetic + 3 Roboflow real images), copied from the pre-T1 checkout; the split the old weights' reported numbers came from.", "sha256": "c261f9d325c708eceb1d54978d611685ed6be8464b3068926c100208025b83ca", "split": "test" + }, + "real_t4_test": { + "classes": [ + "NMOS", + "PMOS", + "VDD", + "GND", + "INPUT_PORT", + "OUTPUT_PORT", + "JUNCTION", + "AND", + "OR", + "NOT", + "NAND", + "NOR", + "XOR", + "XNOR", + "RESISTOR", + "CAPACITOR", + "INDUCTOR", + "BJT_NPN", + "BJT_PNP", + "CLOCK" + ], + "images": 99, + "labels": 99, + "netlists": 0, + "note": "T4 real held-out test split: CGHD drafter_20 (96 photos) + 3 Roboflow source images, tier A+B labels, uncertain_* ignore regions included in the hash; built by python -m real_data.build convert at data_manifest.json split hash f54365743dac2bc7", + "sha256": "863a43e5d84a824839786b17db87f0218e3a6f1259035603c91ed8dae0c21514", + "split": "test" + }, + "synth_v2_seed1_n8000_test": { + "classes": [ + "NMOS", + "PMOS", + "VDD", + "GND", + "INPUT_PORT", + "OUTPUT_PORT", + "JUNCTION", + "AND", + "OR", + "NOT", + "NAND", + "NOR", + "XOR", + "XNOR" + ], + "images": 812, + "labels": 812, + "netlists": 812, + "note": "Synthetic held-out test: backend/data_gen/generate_v2.py --count 8000 --seed 1 test split (topology-hash split, about half in held-out render styles), manifest.json sha256 fdecdb6af9d5f49d5905e5f6f11f16a8caa494c66315543dc265cbb3c1257d3c", + "sha256": "118ae2c024ffe9f01690abe25119a1bce2f1223177910a5af32d28874fb06ffc", + "split": "test" } } diff --git a/ml/kaggle/build_dataset.py b/ml/kaggle/build_dataset.py new file mode 100644 index 0000000..a437abd --- /dev/null +++ b/ml/kaggle/build_dataset.py @@ -0,0 +1,328 @@ +""" +Module: build_dataset.py +Purpose: Assemble the self-contained training dataset for the stage-A / stage-B detector runs (Kaggle or + local) from the two data sources on disk: the synthetic generator v2 output + (backend/data_gen/generate_v2.py) and the converted real data (ml/data_real/yolo, built by + `python -m real_data.build convert`). The output folder is what gets uploaded as one private + Kaggle dataset, so every path inside it is relative. + + What it does to the real data (training copies only, the frozen eval set is never touched): + - keeps tier A labels only (ml/classes.yaml ids are shared, so tier B lines are dropped and + those objects become background, which is correct for a tier A detector); + - downsizes images to at most --real-max-side pixels (labels are normalised, so unchanged); + - paints out `uncertain_*` ignore regions in train/valid (objects T4 could not label: transistors + of undecided polarity, terminals of undecided role, supplies of undecided sign), so the + detector is not taught that a real transistor or port is background. Pixels inside labelled + boxes are never painted. + + Layout written under --out: + synth/{images,labels}/{train,valid,test}/ synthetic samples (file names prefixed syn_) + real/{images,labels}/{train,valid,test}/ real samples (tier A labels) + stage_a.yaml synthetic train / valid / test + stage_b.yaml train = stage_b_synth_train.txt (a synthetic subset; real images are added and + oversampled by the trainer's --real-train real/images/train), val = synthetic + valid + real valid, test = real test + train_kaggle.py, t7_session.py the trainer and the session driver, so the kernel needs no repo + build_info.json counts, settings and source hashes of this build +Usage: + cd ml && uv run python kaggle/build_dataset.py --synth DIR --real data_real/yolo --out OUT +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import shutil +import sys +from collections import Counter +from pathlib import Path + +import cv2 +import numpy as np +import yaml + +ML_DIR = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ML_DIR)) + +from class_schema import load_schema # noqa: E402 + +SPLITS = ("train", "valid", "test") +PAINT_REASONS = ("uncertain_fet", "uncertain_supply", "uncertain_terminal") +PAINT_SPLITS = ("train", "valid") +DEFAULT_REAL_MAX_SIDE = 1920 +DEFAULT_STAGE_B_SYNTH = 2500 +RING_PX = 6 +LABEL_MARGIN_PX = 2 +JPEG_QUALITY = 92 +SEED = 0 + + +def link_or_copy(src: Path, dst: Path) -> None: + """ + Hard-link a file (fast, no extra disk) and fall back to a copy across file systems. + + Args: + src: Existing file. + dst: Destination path (parent created). + """ + dst.parent.mkdir(parents=True, exist_ok=True) + try: + os.link(src, dst) + except OSError: + shutil.copy2(src, dst) + + +def tier_a_lines(label_text: str, n_tier_a: int) -> list[str]: + """ + Keep the YOLO label lines whose class id is a tier A class. + + Args: + label_text: Contents of a YOLO label file. + n_tier_a: Number of tier A classes (ids 0..n-1 in ml/classes.yaml order). + Returns: + The kept lines (without trailing newlines). + Raises: + ValueError: If a line does not start with an integer class id. + """ + kept: list[str] = [] + for line in label_text.splitlines(): + parts = line.split() + if not parts: + continue + if int(parts[0]) < n_tier_a: + kept.append(" ".join(parts)) + return kept + + +def label_boxes_px(lines: list[str], width: int, height: int) -> list[tuple[int, int, int, int]]: + """ + Pixel xyxy boxes of YOLO box lines (polygon lines use their bounding box). + + Args: + lines: YOLO label lines. + width: Image width in pixels. + height: Image height in pixels. + Returns: + Integer xyxy boxes. + """ + boxes: list[tuple[int, int, int, int]] = [] + for line in lines: + vals = [float(v) for v in line.split()[1:]] + if len(vals) == 4: + cx, cy, w, h = vals + x1, y1, x2, y2 = cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2 + else: + xs, ys = vals[0::2], vals[1::2] + x1, y1, x2, y2 = min(xs), min(ys), max(xs), max(ys) + boxes.append((int(x1 * width), int(y1 * height), int(np.ceil(x2 * width)), int(np.ceil(y2 * height)))) + return boxes + + +def paint_regions(image: np.ndarray, regions: list[list[float]], keep: list[tuple[int, int, int, int]]) -> int: + """ + Fill ignore regions with the surrounding paper colour, never touching labelled boxes. + + Args: + image: BGR image, modified in place. + regions: Pixel xyxy boxes to paint. + keep: Pixel xyxy boxes of labelled objects (protected, with a small margin). + Returns: + Number of regions painted. + """ + height, width = image.shape[:2] + protect = np.zeros((height, width), dtype=bool) + for x1, y1, x2, y2 in keep: + protect[max(0, y1 - LABEL_MARGIN_PX) : min(height, y2 + LABEL_MARGIN_PX), max(0, x1 - LABEL_MARGIN_PX) : min(width, x2 + LABEL_MARGIN_PX)] = True + painted = 0 + for box in regions: + x1, y1 = max(0, int(box[0])), max(0, int(box[1])) + x2, y2 = min(width, int(np.ceil(box[2]))), min(height, int(np.ceil(box[3]))) + if x2 <= x1 or y2 <= y1: + continue + rx1, ry1, rx2, ry2 = max(0, x1 - RING_PX), max(0, y1 - RING_PX), min(width, x2 + RING_PX), min(height, y2 + RING_PX) + ring = np.ones((ry2 - ry1, rx2 - rx1), dtype=bool) + ring[y1 - ry1 : y2 - ry1, x1 - rx1 : x2 - rx1] = False + ring_pixels = image[ry1:ry2, rx1:rx2][ring] + if len(ring_pixels) == 0: + continue + # The brightest half of the ring is paper (ink is darker): its median is the fill colour. + brightness = ring_pixels.astype(np.int32).sum(axis=1) + paper = ring_pixels[brightness >= np.median(brightness)] + fill = np.median(paper, axis=0).astype(np.uint8) + mask = ~protect[y1:y2, x1:x2] + if mask.any(): + image[y1:y2, x1:x2][mask] = fill + painted += 1 + return painted + + +def build_real(real_root: Path, out: Path, n_tier_a: int, max_side: int) -> dict[str, object]: + """ + Write the real-data part: tier A labels, downsized images, uncertain regions painted in train/valid. + + Args: + real_root: ml/data_real/yolo (images/, labels/, ignore/ per split). + out: Output dataset root. + n_tier_a: Number of tier A classes. + max_side: Longest image side after downsizing. + Returns: + Per-split image counts, tier A instance counts and painted-region counts. + Raises: + FileNotFoundError: If a split's images directory is missing. + """ + stats: dict[str, object] = {} + for split in SPLITS: + src_images = real_root / "images" / split + if not src_images.is_dir(): + raise FileNotFoundError(f"missing real split {src_images}") + counts: Counter[int] = Counter() + painted = 0 + images = sorted(p for p in src_images.iterdir() if p.is_file()) + for path in images: + label_src = real_root / "labels" / split / f"{path.stem}.txt" + lines = tier_a_lines(label_src.read_text() if label_src.exists() else "", n_tier_a) + counts.update(int(line.split()[0]) for line in lines) + image = cv2.imread(str(path), cv2.IMREAD_COLOR) + if image is None: + raise FileNotFoundError(f"unreadable image {path}") + if split in PAINT_SPLITS: + ignore_file = real_root / "ignore" / split / f"{path.stem}.json" + records = json.loads(ignore_file.read_text()) if ignore_file.exists() else [] + regions = [r["xyxy"] for r in records if r.get("reason") in PAINT_REASONS] + if regions: + painted += paint_regions(image, regions, label_boxes_px(lines, image.shape[1], image.shape[0])) + scale = max_side / max(image.shape[:2]) + if scale < 1.0: + image = cv2.resize(image, (round(image.shape[1] * scale), round(image.shape[0] * scale)), interpolation=cv2.INTER_AREA) + dst = out / "real" / "images" / split / f"{path.stem}.jpg" + dst.parent.mkdir(parents=True, exist_ok=True) + cv2.imwrite(str(dst), image, [cv2.IMWRITE_JPEG_QUALITY, JPEG_QUALITY]) + label_dst = out / "real" / "labels" / split / f"{path.stem}.txt" + label_dst.parent.mkdir(parents=True, exist_ok=True) + label_dst.write_text("".join(f"{line}\n" for line in lines)) + stats[split] = {"images": len(images), "instances": dict(sorted(counts.items())), "painted_regions": painted} + return stats + + +def build_synth(synth_root: Path, out: Path) -> dict[str, int]: + """ + Link the synthetic images and labels in, prefixing file names with `syn_` (the evaluator's domain rule). + + Args: + synth_root: generate_v2.py output folder. + out: Output dataset root. + Returns: + Images per split. + Raises: + FileNotFoundError: If a split's images directory is missing. + """ + counts: dict[str, int] = {} + for split in SPLITS: + src_images = synth_root / "images" / split + if not src_images.is_dir(): + raise FileNotFoundError(f"missing synthetic split {src_images}") + images = sorted(src_images.glob("*.jpg")) + for path in images: + link_or_copy(path, out / "synth" / "images" / split / f"syn_{path.name}") + link_or_copy(synth_root / "labels" / split / f"{path.stem}.txt", out / "synth" / "labels" / split / f"syn_{path.stem}.txt") + counts[split] = len(images) + return counts + + +def write_yamls(out: Path, names: tuple[str, ...], stage_b_synth: int) -> int: + """ + Write stage_a.yaml, stage_b.yaml and the stage-B synthetic subset list. + + Args: + out: Output dataset root. + names: Tier A class names in id order. + stage_b_synth: Synthetic training images kept for stage B (a seeded random subset). + Returns: + Number of synthetic images in the stage-B list. + """ + synth_train = sorted((out / "synth" / "images" / "train").glob("*.jpg")) + rng = np.random.default_rng(SEED) + keep = sorted(rng.choice(len(synth_train), size=min(stage_b_synth, len(synth_train)), replace=False).tolist()) + (out / "stage_b_synth_train.txt").write_text("".join(f"./synth/images/train/{synth_train[i].name}\n" for i in keep)) + # No `path:` key: ultralytics then resolves the splits against the yaml's own folder, wherever the dataset lives + # (a relative `path: .` would resolve against its global datasets dir instead). + common = {"nc": len(names), "names": list(names)} + stage_a = {"train": "synth/images/train", "val": "synth/images/valid", "test": "synth/images/test", **common} + stage_b = {"train": "stage_b_synth_train.txt", "val": ["synth/images/valid", "real/images/valid"], "test": "real/images/test", **common} + (out / "stage_a.yaml").write_text(yaml.safe_dump(stage_a, sort_keys=False)) + (out / "stage_b.yaml").write_text(yaml.safe_dump(stage_b, sort_keys=False)) + return len(keep) + + +def manifest_sha256(path: Path) -> str | None: + """ + SHA-256 of a source manifest file, recorded so a build can be traced back to its inputs. + + Args: + path: Manifest file (may not exist). + Returns: + Hex digest, or None when the file is missing. + """ + return hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None + + +def build(synth_root: Path, real_root: Path, out: Path, real_max_side: int, stage_b_synth: int) -> dict[str, object]: + """ + Build the whole dataset folder. + + Args: + synth_root: generate_v2.py output folder. + real_root: ml/data_real/yolo. + out: Output folder (must not exist yet). + real_max_side: Longest side of the real training copies. + stage_b_synth: Synthetic images kept in the stage-B training list. + Returns: + The build_info.json contents. + Raises: + FileExistsError: If the output folder already exists. + """ + if out.exists(): + raise FileExistsError(f"{out} exists; pick a new --out") + names = tuple(c.name for c in load_schema().classes_up_to("A")) + out.mkdir(parents=True) + synth_counts = build_synth(synth_root, out) + real_stats = build_real(real_root, out, len(names), real_max_side) + stage_b_n = write_yamls(out, names, stage_b_synth) + here = Path(__file__).resolve().parent + for script in ("train_kaggle.py", "t7_session.py"): + shutil.copy2(here / script, out / script) + info: dict[str, object] = { + "classes": list(names), + "synthetic": {"source": str(synth_root), "manifest_sha256": manifest_sha256(synth_root / "manifest.json"), "images": synth_counts}, + "real": {"source": str(real_root), "max_side": real_max_side, "painted_reasons": list(PAINT_REASONS), "splits": real_stats}, + "stage_b_synthetic_train_images": stage_b_n, + } + (out / "build_info.json").write_text(json.dumps(info, indent=2) + "\n") + return info + + +def main(argv: list[str] | None = None) -> int: + """ + CLI entry point. + + Args: + argv: Argument list (defaults to sys.argv[1:]). + Returns: + Process exit code (0 on success). + """ + p = argparse.ArgumentParser(description="Assemble the stage-A/B training dataset folder (synthetic + real)") + p.add_argument("--synth", type=Path, required=True, help="generate_v2.py output folder") + p.add_argument("--real", type=Path, default=ML_DIR / "data_real" / "yolo", help="converted real data (python -m real_data.build convert)") + p.add_argument("--out", type=Path, required=True) + p.add_argument("--real-max-side", type=int, default=DEFAULT_REAL_MAX_SIDE) + p.add_argument("--stage-b-synth", type=int, default=DEFAULT_STAGE_B_SYNTH, help="synthetic training images kept for stage B") + args = p.parse_args(argv) + info = build(args.synth, args.real, args.out, args.real_max_side, args.stage_b_synth) + print(json.dumps(info, indent=2)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ml/kaggle/t7_session.py b/ml/kaggle/t7_session.py new file mode 100644 index 0000000..fedfe67 --- /dev/null +++ b/ml/kaggle/t7_session.py @@ -0,0 +1,124 @@ +""" +Module: t7_session.py +Purpose: Kaggle kernel driver for the T7 training runs: runs train_kaggle.py twice in one GPU session, + stage A (synthetic pretrain from COCO yolov8s) and then stage B (mixed fine-tune of the stage-A + best.pt with the real training images oversampled), each with a wall-clock budget so the whole + session fits the weekly GPU quota. It is pushed as the kernel's code file; the dataset built by + ml/kaggle/build_dataset.py carries train_kaggle.py, stage_a.yaml and stage_b.yaml. + + Stage B always starts fresh from the stage-A weights (never --resume: resuming a stage-B run + loses the oversampling). Outputs: /kaggle/working/stage_a and /kaggle/working/stage_b, each with + best.pt, best.onnx, metrics.json, config.yaml and the ultralytics train/val folders. +Usage (kernel code file; settings come from the constants below or DIGISIM_* environment variables): + python t7_session.py # full session + DIGISIM_SMOKE=1 python t7_session.py # a few minutes per stage to prove the path end to end +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import time +from pathlib import Path + +INPUT_ROOT = Path("/kaggle/input") +WORKING = Path("/kaggle/working") +STAGE_A_HOURS = float(os.environ.get("DIGISIM_STAGE_A_HOURS", "2.8")) +STAGE_B_HOURS = float(os.environ.get("DIGISIM_STAGE_B_HOURS", "1.8")) +SMOKE_HOURS = 0.04 +IMGSZ = int(os.environ.get("DIGISIM_IMGSZ", "960")) +REAL_OVERSAMPLE = int(os.environ.get("DIGISIM_REAL_OVERSAMPLE", "4")) + + +def find_dataset(root: Path = INPUT_ROOT) -> Path: + """ + Locate the attached dataset folder (the one holding stage_a.yaml and train_kaggle.py). + + Args: + root: Kaggle input root. + Returns: + The dataset folder. + Raises: + FileNotFoundError: If no attached dataset has stage_a.yaml. + """ + for depth in range(5): + for hit in sorted(root.glob("/".join(["*"] * depth + ["stage_a.yaml"]))): + if (hit.parent / "train_kaggle.py").is_file(): + return hit.parent + raise FileNotFoundError(f"no dataset with stage_a.yaml and train_kaggle.py under {root}") + + +def run_stage(dataset: Path, args: list[str], log_name: str) -> float: + """ + Run train_kaggle.py with the given arguments, streaming its output to the kernel log and a file. + + Args: + dataset: Dataset folder (holds train_kaggle.py). + args: Arguments for train_kaggle.py. + log_name: Log file name under /kaggle/working. + Returns: + Wall-clock seconds the stage took. + Raises: + subprocess.CalledProcessError: If the trainer exits non-zero. + """ + started = time.time() + cmd = [sys.executable, str(dataset / "train_kaggle.py"), *args] + print("+", " ".join(cmd), flush=True) + with (WORKING / log_name).open("w") as log: + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, cwd=str(WORKING)) + assert proc.stdout is not None + for line in proc.stdout: + sys.stdout.write(line) + log.write(line) + code = proc.wait() + if code != 0: + raise subprocess.CalledProcessError(code, cmd) + return time.time() - started + + +def main() -> int: + """ + Run stage A then stage B and write a session summary. + + Returns: + Process exit code (0 on success). + """ + smoke = os.environ.get("DIGISIM_SMOKE") == "1" + hours_a = SMOKE_HOURS if smoke else STAGE_A_HOURS + hours_b = SMOKE_HOURS if smoke else STAGE_B_HOURS + dataset = find_dataset() + print(f"dataset: {dataset} smoke={smoke} stage A {hours_a} h, stage B {hours_b} h, imgsz {IMGSZ}", flush=True) + subprocess.check_call(["nvidia-smi"]) + summary: dict[str, object] = {"dataset": str(dataset), "smoke": smoke, "imgsz": IMGSZ} + common = ["--device", "auto", "--imgsz", str(IMGSZ)] + out_a = WORKING / "stage_a" + summary["stage_a_seconds"] = run_stage(dataset, ["--preset", "stage-a", "--data", str(dataset / "stage_a.yaml"), "--time", str(hours_a), "--out", str(out_a), *common], "stage_a.log") + out_b = WORKING / "stage_b" + stage_b_args = [ + "--preset", + "stage-b", + "--data", + str(dataset / "stage_b.yaml"), + "--model", + str(out_a / "best.pt"), + "--real-train", + "real/images/train", + "--real-oversample", + str(REAL_OVERSAMPLE), + "--time", + str(hours_b), + "--out", + str(out_b), + "--skip-install", + *common, + ] + summary["stage_b_seconds"] = run_stage(dataset, stage_b_args, "stage_b.log") + (WORKING / "session_summary.json").write_text(json.dumps(summary, indent=2) + "\n") + print(json.dumps(summary, indent=2)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ml/kaggle/train_kaggle.py b/ml/kaggle/train_kaggle.py index 3f1f89c..b720f05 100644 --- a/ml/kaggle/train_kaggle.py +++ b/ml/kaggle/train_kaggle.py @@ -428,6 +428,7 @@ def build_plan(args: argparse.Namespace) -> dict[str, Any]: "batch_total": resolve_batch(args.batch if args.batch is not None else saved_batch, preset.batch_per_device, world), "workers": args.workers if args.workers is not None else default_workers(), "epochs": args.epochs if args.epochs is not None else int(saved.get("epochs") or preset.epochs), + "time_hours": args.time if args.time is not None else (float(saved["time_hours"]) if saved.get("time_hours") else None), "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), @@ -490,6 +491,7 @@ def run(plan: dict[str, Any], install: bool) -> Path: warmup_epochs=plan["warmup_epochs"], close_mosaic=plan["close_mosaic"], plots=plan["plots"], + **({"time": plan["time_hours"]} if plan["time_hours"] else {}), project=str(out), name="train", exist_ok=True, @@ -519,7 +521,7 @@ def run(plan: dict[str, Any], install: bool) -> Path: "gate": gate_verdict(per_class), "class_names": [best_model.names[i] for i in sorted(best_model.names)], "dataset": {"data": plan["data_yaml"], "data_effective": str(data_yaml), **{f"{k}_images": v for k, v in counts.items()}, "real_oversample": plan["real_oversample"]}, - "settings": {k: plan[k] for k in ("model", "epochs", "imgsz", "device", "workers", "seed", "lr0")} | {"batch": plan["batch_total"]}, + "settings": {k: plan[k] for k in ("model", "epochs", "time_hours", "imgsz", "device", "workers", "seed", "lr0")} | {"batch": plan["batch_total"]}, "environment": environment_info(), "train_seconds": round(time.time() - started, 1), "weights": str(out / "best.pt"), @@ -547,6 +549,7 @@ def build_parser() -> argparse.ArgumentParser: 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("--time", type=float, default=None, help="wall-clock training budget in hours; overrides --epochs (ultralytics fits the epoch count and LR schedule to it)") 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) diff --git a/ml/tests/test_eval_frozen.py b/ml/tests/test_eval_frozen.py index 311b344..f85a284 100644 --- a/ml/tests/test_eval_frozen.py +++ b/ml/tests/test_eval_frozen.py @@ -103,3 +103,17 @@ def test_hash_follows_the_directories_it_is_given(tmp_path: Path) -> None: (other / "pics" / "syn_0.jpg").write_bytes(b"image-bytes") (other / "tags" / "syn_0.txt").write_text("0 0.5 0.5 0.1 0.1\n") assert hash_split(other / "pics", other / "tags", other / "none", NAMES).sha256 == hash_test_split(root, NAMES).sha256 + + +def test_ignore_regions_join_the_hash_only_when_present(tmp_path: Path) -> None: + """A split without ignore regions hashes as before; adding or editing an ignore file changes the hash.""" + root = make_dataset(tmp_path / "d") + ignore = root / "ignore" / "test" + plain = hash_test_split(root, NAMES).sha256 + assert hash_split(root / "images" / "test", root / "labels" / "test", root / "netlists" / "test", NAMES, ignore).sha256 == plain + ignore.mkdir(parents=True) + (ignore / "syn_0.json").write_text('[{"reason": "uncertain_fet", "xyxy": [0, 0, 5, 5]}]') + with_ignore = hash_split(root / "images" / "test", root / "labels" / "test", root / "netlists" / "test", NAMES, ignore).sha256 + assert with_ignore != plain + (ignore / "syn_0.json").write_text('[{"reason": "uncertain_fet", "xyxy": [0, 0, 6, 5]}]') + assert hash_split(root / "images" / "test", root / "labels" / "test", root / "netlists" / "test", NAMES, ignore).sha256 != with_ignore diff --git a/ml/tests/test_eval_metrics.py b/ml/tests/test_eval_metrics.py index 8061ec2..e09f521 100644 --- a/ml/tests/test_eval_metrics.py +++ b/ml/tests/test_eval_metrics.py @@ -7,7 +7,7 @@ import numpy as np import pytest -from eval_metrics import DetectionAccumulator, box_iou, domain_for, match_boxes, parse_domain_rule, rate, wilson_interval +from eval_metrics import DetectionAccumulator, box_iou, domain_for, drop_ignored, match_boxes, parse_domain_rule, rate, wilson_interval def gt_rows(*rows: tuple[int, float, float, float, float]) -> np.ndarray: @@ -108,3 +108,24 @@ def test_domains() -> None: assert parse_domain_rule("cghd_=cghd_real") == ("cghd_", "cghd_real") with pytest.raises(ValueError): parse_domain_rule("nonsense") + + +def test_drop_ignored_masks_only_unmatched_predictions_inside_ignore_boxes() -> None: + """ + A prediction inside an ignore box is dropped unless it matches ground truth; predictions elsewhere are kept. + """ + gt = np.array([[0, 0, 0, 10, 10]], dtype=float) + pred = np.array( + [ + [0, 0.9, 0, 0, 10, 10], # matches GT (also inside the ignore box): kept + [1, 0.8, 52, 52, 58, 58], # unmatched, fully inside the ignore box: dropped + [1, 0.7, 80, 80, 90, 90], # unmatched, outside: kept (a real false positive) + [1, 0.6, 50, 50, 70, 70], # unmatched, only 25% inside: kept + ] + ) + ignore = np.array([[0, 0, 60, 60]], dtype=float) + kept, dropped = drop_ignored(gt, pred, ignore) + assert dropped == 1 + assert kept[:, 1].tolist() == [0.9, 0.7, 0.6] + same, none = drop_ignored(gt, pred, np.zeros((0, 4))) + assert none == 0 and len(same) == len(pred) diff --git a/ml/tests/test_evaluate.py b/ml/tests/test_evaluate.py index 46de0c8..e519bdd 100644 --- a/ml/tests/test_evaluate.py +++ b/ml/tests/test_evaluate.py @@ -18,12 +18,22 @@ import evaluate from eval_metrics import DetectionAccumulator from eval_report import render_markdown -from evaluate import DatasetInfo, build_class_map, load_dataset_info, main, read_labels, reproduction_check, sibling_dir +from evaluate import DatasetInfo, build_class_map, evaluate_detection, load_dataset_info, main, read_labels, reproduction_check, sibling_dir DETECTOR_CALLS: list[Path] = [] -def stub_detection(info: DatasetInfo, weights: Path, imgsz: int, conf: float, iou: float, small_px: float, device: str, domain_rules: tuple[tuple[str, str], ...]) -> dict: +def stub_detection( + info: DatasetInfo, + weights: Path, + imgsz: int, + conf: float, + iou: float, + small_px: float, + device: str, + domain_rules: tuple[tuple[str, str], ...], + ignore_reasons: tuple[str, ...] = (), +) -> dict: """ Stand-in for evaluate_detection: an empty but schema-complete detection block, recording that it ran. @@ -36,6 +46,7 @@ def stub_detection(info: DatasetInfo, weights: Path, imgsz: int, conf: float, io small_px: Small-object threshold. device: Device (unused). domain_rules: Domain rules (unused). + ignore_reasons: Ignore-region reasons (unused). Returns: A detection dict with no ground truth and no predictions. """ @@ -231,3 +242,44 @@ def test_labels_and_netlists_dirs_swap_the_last_images_component(tmp_path: Path) assert info.netlists_dir == root / "netlists" / "test" with pytest.raises(ValueError): sibling_dir(Path("/data/test"), "labels") + + +def test_detection_masks_uncertain_ignore_regions_but_scores_unmapped_ones(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """ + An unmatched prediction inside an `uncertain_*` ignore region is not a false positive; one inside an + `unmapped` region (a real object outside the vocabulary) still is. + """ + root = tmp_path / "d" + for sub in ("images", "labels", "ignore"): + (root / sub / "test").mkdir(parents=True) + (root / "images" / "test" / "cghd_0.jpg").write_bytes(b"x") + (root / "labels" / "test" / "cghd_0.txt").write_text("0 0.05 0.05 0.1 0.1\n") + regions = [{"reason": "uncertain_fet", "xyxy": [40, 40, 60, 60]}, {"reason": "unmapped", "xyxy": [70, 70, 90, 90]}] + (root / "ignore" / "test" / "cghd_0.json").write_text(json.dumps(regions)) + (root / "data.yaml").write_text("path: .\ntest: images/test\nnames: [NMOS, PMOS]\n") + preds = np.array([[0, 0.9, 0, 0, 10, 10], [0, 0.8, 42, 42, 58, 58], [1, 0.7, 72, 72, 88, 88]]) + monkeypatch.setattr(evaluate, "predict_split", lambda *a, **k: ({0: "NMOS", 1: "PMOS"}, {"cghd_0.jpg": (preds, (100, 100))})) + info = load_dataset_info(root / "data.yaml", "test") + det = evaluate_detection(info, Path("w.pt"), 640, 0.35, 0.5, 24.0, "cpu", ()) + assert det["ignore_masking"] == {"reasons": list(evaluate.DEFAULT_IGNORE_REASONS), "regions": 1, "dropped_predictions": 1} + assert det["per_class"]["NMOS"]["fp"] == 0 and det["per_class"]["PMOS"]["fp"] == 1 + unmasked = evaluate_detection(info, Path("w.pt"), 640, 0.35, 0.5, 24.0, "cpu", (), ()) + assert unmasked["per_class"]["NMOS"]["fp"] == 1 and unmasked["ignore_masking"]["dropped_predictions"] == 0 + + +def test_detection_splits_held_out_style_images_into_their_own_domain(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Images the generate_v2 manifest flags held_out_style are scored under `_heldout_style`.""" + root = tmp_path / "d" + for sub in ("images", "labels"): + (root / sub / "test").mkdir(parents=True) + for stem in ("000001", "000002"): + (root / "images" / "test" / f"{stem}.jpg").write_bytes(b"x") + (root / "labels" / "test" / f"{stem}.txt").write_text("0 0.05 0.05 0.1 0.1\n") + samples = [{"files": {"image": {"path": f"images/test/{s}.jpg"}}, "held_out_style": s == "000002"} for s in ("000001", "000002")] + (root / "manifest.json").write_text(json.dumps({"samples": samples})) + (root / "data.yaml").write_text("path: .\ntest: images/test\nnames: [NMOS, PMOS]\n") + hit = np.array([[0, 0.9, 0, 0, 10, 10]]) + monkeypatch.setattr(evaluate, "predict_split", lambda *a, **k: ({0: "NMOS", 1: "PMOS"}, {f"{s}.jpg": (hit, (100, 100)) for s in ("000001", "000002")})) + det = evaluate_detection(load_dataset_info(root / "data.yaml", "test"), Path("w.pt"), 640, 0.35, 0.5, 24.0, "cpu", (("0", "synthetic"),)) + assert sorted(det["per_domain"]) == ["synthetic", "synthetic_heldout_style"] + assert det["per_domain"]["synthetic_heldout_style"]["overall"]["images"] == 1 and det["per_class"]["NMOS"]["tp"] == 2 diff --git a/ml/tests/test_kaggle_build.py b/ml/tests/test_kaggle_build.py new file mode 100644 index 0000000..1ab2179 --- /dev/null +++ b/ml/tests/test_kaggle_build.py @@ -0,0 +1,82 @@ +""" +Module: test_kaggle_build.py +Purpose: Tests for ml/kaggle/build_dataset.py (tier A filtering, ignore-region painting that never touches + labelled objects, the stage-A/B dataset layout) and ml/kaggle/t7_session.py (dataset discovery). +""" + +import importlib.util +import json +import sys +from pathlib import Path +from types import ModuleType + +import cv2 +import numpy as np +import pytest +import yaml + +KAGGLE_DIR = Path(__file__).resolve().parent.parent / "kaggle" + + +def load(name: str) -> ModuleType: + """ + Import a script from ml/kaggle by file path (the folder is not a package). + + Args: + name: Module file stem. + Returns: + The loaded module. + """ + spec = importlib.util.spec_from_file_location(name, KAGGLE_DIR / f"{name}.py") + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +build_dataset = load("build_dataset") +t7_session = load("t7_session") + + +def test_tier_a_lines_drop_tier_b_classes() -> None: + """Ids below the tier A count are kept, tier B ids (14+) are dropped, blank lines vanish.""" + text = "0 0.5 0.5 0.1 0.1\n14 0.2 0.2 0.1 0.1\n\n13 0.3 0.3 0.1 0.1\n" + assert build_dataset.tier_a_lines(text, 14) == ["0 0.5 0.5 0.1 0.1", "13 0.3 0.3 0.1 0.1"] + + +def test_paint_regions_fills_with_paper_and_protects_labels() -> None: + """An ignore region becomes paper-coloured, except where it overlaps a labelled box.""" + image = np.full((100, 100, 3), 240, dtype=np.uint8) + image[20:40, 20:40] = 10 # ink of an object we could not label + image[30:40, 30:40] = 50 # ink of a labelled object overlapping the region + painted = build_dataset.paint_regions(image, [[20, 20, 40, 40]], [(32, 32, 40, 40)]) + assert painted == 1 + assert (image[20:28, 20:28] == 240).all() + assert (image[34:40, 34:40] == 50).all() + + +def test_build_writes_stage_layouts(tmp_path: Path) -> None: + """A tiny synthetic + real pair builds both yamls, prefixes synthetic names and keeps real labels tier A only.""" + synth = tmp_path / "synth" + real = tmp_path / "real" + for split in ("train", "valid", "test"): + for root, stem in ((synth, "000001"), (real, "cghd_x")): + (root / "images" / split).mkdir(parents=True) + (root / "labels" / split).mkdir(parents=True) + cv2.imwrite(str(root / "images" / split / f"{stem}.jpg"), np.full((60, 80, 3), 255, dtype=np.uint8)) + (root / "labels" / split / f"{stem}.txt").write_text("0 0.5 0.5 0.2 0.2\n15 0.1 0.1 0.1 0.1\n") + (real / "ignore" / "train").mkdir(parents=True) + (real / "ignore" / "train" / "cghd_x.json").write_text(json.dumps([{"reason": "uncertain_fet", "xyxy": [0, 0, 10, 10]}])) + out = tmp_path / "out" + info = build_dataset.build(synth, real, out, real_max_side=40, stage_b_synth=5) + assert (out / "synth" / "images" / "train" / "syn_000001.jpg").is_file() + assert (out / "real" / "labels" / "test" / "cghd_x.txt").read_text() == "0 0.5 0.5 0.2 0.2\n" + assert max(cv2.imread(str(out / "real" / "images" / "train" / "cghd_x.jpg")).shape[:2]) == 40 + stage_b = yaml.safe_load((out / "stage_b.yaml").read_text()) + assert stage_b["val"] == ["synth/images/valid", "real/images/valid"] and stage_b["test"] == "real/images/test" + assert (out / "stage_b_synth_train.txt").read_text() == "./synth/images/train/syn_000001.jpg\n" + assert info["real"]["splits"]["train"]["painted_regions"] == 1 + assert (out / "train_kaggle.py").is_file() and t7_session.find_dataset(tmp_path) == out + with pytest.raises(FileExistsError): + build_dataset.build(synth, real, out, 40, 5) diff --git a/ml/train.py b/ml/train.py index 8babe57..944d972 100644 --- a/ml/train.py +++ b/ml/train.py @@ -122,6 +122,7 @@ class TrainConfig: project: Path name: str epochs: int + time_hours: float | None imgsz: int batch: int device: DevicePlan @@ -437,6 +438,7 @@ def resolve_config(args: argparse.Namespace) -> TrainConfig: 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), + time_hours=args.time if args.time is not None else (float(str(saved["time_hours"])) if saved.get("time_hours") else None), imgsz=args.imgsz if args.imgsz is not None else int(saved.get("imgsz") or preset.imgsz), batch=resolve_batch(args.batch if args.batch is not None else saved_batch, preset.batch_per_device, plan), device=plan, @@ -491,6 +493,7 @@ def describe_plan(cfg: TrainConfig) -> dict[str, object]: "batch_per_process": cfg.batch // cfg.device.world_size if cfg.batch > 0 else cfg.batch, "workers": cfg.workers, "epochs": cfg.epochs, + "time_hours": cfg.time_hours, "imgsz": cfg.imgsz, "lr0": cfg.lr0, "patience": cfg.patience, @@ -628,6 +631,7 @@ def train(cfg: TrainConfig) -> Path: "imgsz": cfg.imgsz, "batch": cfg.batch, "device": cfg.device.spec, + **({"time": cfg.time_hours} if cfg.time_hours else {}), "workers": cfg.workers, "patience": cfg.patience, "seed": cfg.seed, @@ -692,7 +696,17 @@ def train(cfg: TrainConfig) -> Path: "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}, + "settings": { + "model": cfg.model, + "epochs": cfg.epochs, + "time_hours": cfg.time_hours, + "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"), @@ -722,6 +736,7 @@ def build_parser() -> argparse.ArgumentParser: 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("--time", type=float, default=None, help="wall-clock training budget in hours; overrides --epochs (ultralytics fits the epoch count and LR schedule to it)") 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)")