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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 63 additions & 1 deletion agent_docs/ml-pipeline.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,12 @@ 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).
`--augment default | strong` (both trainers; profiles in `AUGMENT_PROFILES`, kept equal in both files) adds real-photo augmentation (hsv, rotation, shear, perspective, wider scale, light mixup) and is recorded in `metrics.json` settings.
`--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/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. `DIGISIM_MODE=retrain` runs only a second stage B from an attached stage-A `best.pt` (see the T7 retrain section).
`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
Expand Down Expand Up @@ -218,6 +219,67 @@ The kernel ran `ml/kaggle/t7_session.py` (ultralytics 8.4.215, torch 2.11 cu130)
- 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.

### T7 retrain cycle (2026-11-18): gates still NOT met

One retrain cycle aimed at the causes above: `DIGISIM_MODE=retrain` in `ml/kaggle/t7_session.py`
([digisim-t7-retrain](https://www.kaggle.com/code/manijos/digisim-t7-retrain), private, Kaggle 2x T4).
It starts from the Run A stage A `best.pt` and changes four things at once:
- **Selection on real images only.** Validation is the 100 drafter-16 images, and early stopping is off (patience 1000).
- **More real data.** The real training images are oversampled x8.
- **Stronger augmentation** (`--augment strong`).
- **Targeted synthetic boost.** Training uses 3370 synthetic images: all 1870 with a gate, plus the 1500 gate-free images richest in VDD, GND and INPUT_PORT.

The boosted class targets (VDD, GND, INPUT_PORT, gates) came from Run A's test-set misses, as directed by main. Checkpoint selection used only the real validation set (drafter 16). The retrain numbers below are therefore slightly optimistic for the boosted classes.

Training ran at imgsz 1280 for 1.45 h, 29 epochs. The best real-validation epoch was 26.

An accidental second full Run A session (the kernel mounted the previous dataset version) gives a **replicate** of stage B with identical settings. It measures run-to-run noise.

| real test (`real_t4_test`), F1 | Run A stage B | replicate stage B | retrain |
|---|---|---|---|
| NMOS (116) | 0.601 | 0.230 | 0.244 [0.19, 0.31] |
| PMOS (78) | 0.564 | 0.400 | 0.553 [0.47, 0.64] |
| VDD (140) | 0.215 | 0.235 | 0.346 [0.28, 0.42] |
| GND (551) | 0.630 | 0.661 | 0.680 [0.65, 0.71] |
| INPUT_PORT (52) | 0.147 | 0.100 | 0.149 [0.08, 0.25] |
| JUNCTION (5124) | 0.758 | 0.747 | 0.760 [0.75, 0.77] |
| AND (101) | 0.507 | 0.443 | 0.407 [0.34, 0.48] |
| OR (35) | 0.436 | 0.393 | 0.853 [0.75, 0.92] |
| **JUNCTION recall** | 0.729 | 0.731 | 0.720 [0.71, 0.73] |
| tier A micro F1 | 0.722 | 0.711 | 0.724 |

On the synthetic held-out styles, the retrain still fails **VDD (0.730 / 0.724)**. It also newly fails OR (0.945 / 0.945).
XOR passes (0.953 / 0.981). The replicate passes XOR too, so the Run A XOR miss was noise.
On the seen styles, every class is >= 0.99.

**Reading.** The retrain does not move the pooled numbers: tier A F1 is 0.724 against 0.722 / 0.711, and JUNCTION recall is 0.720 against 0.729.
- **Resolution was not the junction bottleneck.** Training and evaluating at 1280 did not raise JUNCTION recall, which weakens the small-object explanation.
- **Real-validation fitness plateaued by epoch 5** (0.47 to 0.48 for the rest of the run). More epochs or a longer budget would not help.
- **Per-class changes, judged against the replicate spread:**
- OR (0.44 to 0.85) and VDD (0.22 to 0.35) are the only gains clearly outside it.
- OR reaches the 0.85 line only nominally: n=35, CI [0.75, 0.92].
- NMOS (0.60, 0.23, 0.24 across the three runs) shows that NMOS/PMOS polarity on drafter 20 is close to a coin flip between runs.

**Conclusion:** selection, augmentation and resampling are exhausted on the current real data, and the remaining gap is real-data coverage.

Artifacts (outside git): `kaggle_out/retrain/stage_b_retrain/best.pt` sha256 `c0f03b40137e4b2421bb4239aaa34ecdfca5d1f81a8f38f2cef1245fe1dea826`;
`best.onnx` `786720e1...bb03`; `metrics.json` `1e9116a8...65fc1`; `eval/retrain_b_real.json` `c125fba68f3de625...f25d`; `eval/retrain_b_synth.json` `f1b93340f9203f9d...11ad`.
Replicate stage B weights: `kaggle_out/run_a_replicate/stage_b/best.pt` (`5fbfa077...`).

**Extra real data that would help most** (in priority order):
1. **More CGHD drafters with tier A labels.** Aim for at least 10 training drafters, about 1000 images; we have 2 drafters and 231 images today.
The run-to-run spread and the plateau both point to drafter coverage, not model capacity.
Grow the validation split to 2 or 3 drafters too, so checkpoint selection is less noisy than one drafter's 100 images.
2. **Per class, the most needed, with targets of roughly 300+ training instances from 5+ drafters each:**
- VDD and INPUT_PORT: F1 0.35 and 0.15, despite 184 and 207 training instances from only 2 drafters.
- NMOS/PMOS polarity: the 0.23 to 0.60 swings.
- OUTPUT_PORT: 28 test instances.
3. **Gates, which CGHD barely has** (test NOT 10, NAND 1, NOR 1, XOR 1, XNOR 0).
Real gate photos need a source beyond CGHD (for example our own drafters), with at least 30 test instances per gate so the gate can be judged at all.
4. **Resolve the 907 `uncertain_terminal` regions** in the existing real train set (no new drafters needed).
5. **Synthetic:** more VDD symbol variants and line styles in the training styles (keep `circle` held out).
This is the only fix for the synthetic VDD miss, which none of the three runs passes.

## Key Principle
Dataset quality > annotation correctness > pipeline correctness > model architecture.
Fix data before changing models.
Expand Down
135 changes: 135 additions & 0 deletions ml/kaggle/t7_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,16 @@
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.

DIGISIM_MODE=retrain runs only a second stage B from an earlier session's stage-A best.pt (attach that
kernel's output): checkpoint selection on the real validation images only, no early stopping, stronger
real oversampling and augmentation, and a synthetic subset boosted towards the classes that missed the
gate (every gate image plus the transistor images richest in VDD, GND and INPUT_PORT).
Output: /kaggle/working/stage_b_retrain.
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
DIGISIM_MODE=retrain python t7_session.py # stage B retrain from an attached stage_a/best.pt
"""

from __future__ import annotations
Expand All @@ -30,6 +37,16 @@
SMOKE_HOURS = 0.04
IMGSZ = int(os.environ.get("DIGISIM_IMGSZ", "960"))
REAL_OVERSAMPLE = int(os.environ.get("DIGISIM_REAL_OVERSAMPLE", "4"))
RETRAIN_HOURS = float(os.environ.get("DIGISIM_RETRAIN_HOURS", "1.4"))
RETRAIN_IMGSZ = int(os.environ.get("DIGISIM_RETRAIN_IMGSZ", "1280"))
RETRAIN_BATCH = int(os.environ.get("DIGISIM_RETRAIN_BATCH", "16"))
RETRAIN_OVERSAMPLE = int(os.environ.get("DIGISIM_RETRAIN_OVERSAMPLE", "8"))
RETRAIN_TRANSISTOR_IMAGES = int(os.environ.get("DIGISIM_RETRAIN_TRANSISTOR_IMAGES", "1500"))
# Classes the boosted synthetic subset favours: every image with a gate, then images richest in these.
BOOST_GATES = ("AND", "OR", "NOT", "NAND", "NOR", "XOR", "XNOR")
BOOST_TERMINALS = ("VDD", "GND", "INPUT_PORT")
# Patience longer than any budgeted run: selection is by best real-validation fitness, never an early stop.
NO_EARLY_STOP = 1000


def find_dataset(root: Path = INPUT_ROOT) -> Path:
Expand All @@ -50,6 +67,78 @@ def find_dataset(root: Path = INPUT_ROOT) -> Path:
raise FileNotFoundError(f"no dataset with stage_a.yaml and train_kaggle.py under {root}")


def find_stage_a_weights(root: Path = INPUT_ROOT) -> Path:
"""
Locate stage_a/best.pt in an attached earlier session's output.

Args:
root: Kaggle input root.
Returns:
The weights file.
Raises:
FileNotFoundError: If no attached input holds stage_a/best.pt.
"""
for depth in range(5):
hits = sorted(root.glob("/".join(["*"] * depth + ["stage_a", "best.pt"])))
if hits:
return hits[0]
raise FileNotFoundError(f"no stage_a/best.pt under {root}: attach the earlier session's output")


def boosted_synth_images(dataset: Path, names: list[str], transistor_images: int) -> list[Path]:
"""
The synthetic training subset for the retrain: every image with a gate, plus the transistor images richest in supplies and inputs.

Args:
dataset: Dataset folder (holds synth/images/train and synth/labels/train).
names: Class names in id order.
transistor_images: How many gate-free images to add, most VDD + GND + INPUT_PORT instances first (ties by name).
Returns:
Absolute image paths, gate images first.
"""
gate_ids = {str(names.index(n)) for n in BOOST_GATES}
terminal_ids = {str(names.index(n)) for n in BOOST_TERMINALS}
gates: list[Path] = []
others: list[tuple[int, str, Path]] = []
for label in sorted((dataset / "synth" / "labels" / "train").glob("*.txt")):
image = dataset / "synth" / "images" / "train" / f"{label.stem}.jpg"
ids = [line.split()[0] for line in label.read_text().splitlines() if line.strip()]
if gate_ids & set(ids):
gates.append(image)
else:
others.append((-sum(i in terminal_ids for i in ids), label.stem, image))
return gates + [image for _, _, image in sorted(others)[:transistor_images]]


def write_retrain_yaml(dataset: Path, out_dir: Path, transistor_images: int) -> Path:
"""
Write the retrain dataset yaml: boosted synthetic train list, real-only validation, real test (reported, never selected on).

Args:
dataset: Dataset folder (holds stage_b.yaml, synth/ and real/).
out_dir: Writable folder for the yaml and the train list.
transistor_images: Gate-free synthetic images to include (see boosted_synth_images).
Returns:
Path of the written yaml (absolute paths throughout, so it works from any folder).
"""
import yaml

names = list(yaml.safe_load((dataset / "stage_b.yaml").read_text())["names"])
out_dir.mkdir(parents=True, exist_ok=True)
train_list = out_dir / "synth_boost.txt"
train_list.write_text("".join(f"{p.resolve()}\n" for p in boosted_synth_images(dataset, names, transistor_images)))
cfg = {
"train": str(train_list),
"val": str((dataset / "real" / "images" / "valid").resolve()),
"test": str((dataset / "real" / "images" / "test").resolve()),
"nc": len(names),
"names": names,
}
out = out_dir / "retrain.yaml"
out.write_text(yaml.safe_dump(cfg, sort_keys=False))
return out


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.
Expand Down Expand Up @@ -85,6 +174,8 @@ def main() -> int:
Returns:
Process exit code (0 on success).
"""
if os.environ.get("DIGISIM_MODE") == "retrain":
return retrain()
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
Expand Down Expand Up @@ -120,5 +211,49 @@ def main() -> int:
return 0


def retrain() -> int:
"""
Run the stage-B retrain from an attached stage-A best.pt and write a session summary.

Returns:
Process exit code (0 on success).
"""
dataset = find_dataset()
weights = find_stage_a_weights()
data_yaml = write_retrain_yaml(dataset, WORKING / "retrain_data", RETRAIN_TRANSISTOR_IMAGES)
print(f"retrain: dataset {dataset}, base {weights}, {RETRAIN_HOURS} h at imgsz {RETRAIN_IMGSZ}", flush=True)
subprocess.check_call(["nvidia-smi"])
args = [
"--preset",
"stage-b",
"--data",
str(data_yaml),
"--model",
str(weights),
"--real-train",
str((dataset / "real" / "images" / "train").resolve()),
"--real-oversample",
str(RETRAIN_OVERSAMPLE),
"--augment",
"strong",
"--patience",
str(NO_EARLY_STOP),
"--time",
str(RETRAIN_HOURS),
"--imgsz",
str(RETRAIN_IMGSZ),
"--batch",
str(RETRAIN_BATCH),
"--device",
"auto",
"--out",
str(WORKING / "stage_b_retrain"),
]
summary = {"mode": "retrain", "dataset": str(dataset), "base_weights": str(weights), "imgsz": RETRAIN_IMGSZ, "seconds": run_stage(dataset, args, "stage_b_retrain.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())
13 changes: 12 additions & 1 deletion ml/kaggle/train_kaggle.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,14 @@ class Preset:
plots: bool


# Augmentation profiles (ultralytics train hyperparameters on top of its defaults). "strong" targets real hand-drawn
# photos: lighting/paper colour (hsv), small rotation, shear and perspective of a hand-held camera, wider scale range
# for small junctions, and light mixup. Keep this table equal to ml/train.py (tests assert it).
AUGMENT_PROFILES: dict[str, dict[str, float]] = {
"default": {},
"strong": {"hsv_s": 0.6, "hsv_v": 0.5, "degrees": 5.0, "translate": 0.15, "scale": 0.6, "shear": 2.0, "perspective": 0.0005, "mixup": 0.1},
}

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),
Expand Down Expand Up @@ -436,6 +444,7 @@ def build_plan(args: argparse.Namespace) -> dict[str, Any]:
"warmup_epochs": preset.warmup_epochs,
"close_mosaic": preset.close_mosaic,
"plots": preset.plots if args.plots is None else args.plots,
"augment": args.augment or str(saved.get("augment") or "default"),
"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,
Expand Down Expand Up @@ -491,6 +500,7 @@ def run(plan: dict[str, Any], install: bool) -> Path:
warmup_epochs=plan["warmup_epochs"],
close_mosaic=plan["close_mosaic"],
plots=plan["plots"],
**AUGMENT_PROFILES[plan["augment"]],
**({"time": plan["time_hours"]} if plan["time_hours"] else {}),
project=str(out),
name="train",
Expand Down Expand Up @@ -521,7 +531,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", "time_hours", "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", "patience", "augment")} | {"batch": plan["batch_total"]},
"environment": environment_info(),
"train_seconds": round(time.time() - started, 1),
"weights": str(out / "best.pt"),
Expand Down Expand Up @@ -557,6 +567,7 @@ def build_parser() -> argparse.ArgumentParser:
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("--augment", choices=sorted(AUGMENT_PROFILES), default=None, help="augmentation profile (default: default; strong: real-photo augmentation, see AUGMENT_PROFILES)")
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")
Expand Down
Loading
Loading