"""Bounded train-street development selection; exposed controls evaluated once afterwards. No coordinates, street identity or hand-coded geometry enters the classifier. Unknown pixels stay unknown. Every fold excludes a physical area from sampling, normalization and fitting. The immutable admission split is not rewritten. """ import argparse import json import time from pathlib import Path import numpy as np from nonlinear_head_probe import fit_mlp, mlp_logits from pixel_growth_probe import aggregate, counts, fit from supervision_density_probe import samples def folds(records): train = [r for r in records if r["split"] == "train"] if len({r["sample_id"] for r in records}) != len(records): raise ValueError("Duplicate sample") groups = sorted({r["group"] for r in train}) if len(groups) < 3: raise ValueError("At least three training streets required") for group in groups: held = [r for r in train if r["group"] == group] learn = [r for r in train if r["group"] != group] if {r["input"]["rgb"]["sha256"] for r in held} & { r["input"]["rgb"]["sha256"] for r in learn }: raise ValueError("Identical RGB across folds") yield group, learn, held def select_candidate(rows, baseline): """No control inputs accepted; macro BER, with a worst-street guard.""" if not rows or any(r["phase"] != "development" for r in rows): raise ValueError("Development results only") candidates = sorted({r["candidate"] for r in rows}) all_groups = {r["held_out"] for r in rows} if len(all_groups) < 3: raise ValueError("Incomplete development streets") summaries = {} for candidate in candidates: rr = [r for r in rows if r["candidate"] == candidate] if len(rr) != len(all_groups) or {r["held_out"] for r in rr} != all_groups: raise ValueError("Missing or duplicate fold") errors = [] for r in rr: m = r["metrics"] if m["recall"] is None or m["fpr"] is None: raise ValueError("Both classes required per development street") errors.append((1 - m["recall"] + m["fpr"]) / 2) summaries[candidate] = dict( macro_ber=float(np.mean(errors)), worst_ber=max(errors), converged=all(r["converged"] for r in rr), ) base = summaries[baseline] if not base["converged"]: raise ValueError("Reference fit failed") eligible = [ c for c in candidates if summaries[c]["converged"] and summaries[c]["macro_ber"] < base["macro_ber"] - 1e-12 and summaries[c]["worst_ber"] <= base["worst_ber"] + 1e-12 ] winner = ( min(eligible, key=lambda c: (summaries[c]["macro_ber"], summaries[c]["worst_ber"], c)) if eligible else baseline ) return dict( selected=winner, development_improved=bool(eligible), summaries=summaries, rule="lower macro BER; worst-street BER not higher; rank macro, worst, id", ) def features(z, representation): if representation == "semantic": return z["features"].astype("float32") if representation == "detail": return z["detail"].astype("float32") if representation == "combined": return np.concatenate([z["features"], z["detail"]], axis=0).astype("float32") raise ValueError("Unknown representation") def feature_pixels(f, size, indices): import torch h, w = size y, x = np.unravel_index(indices, (h, w)) grid = np.stack([2 * (x + 0.5) / w - 1, 2 * (y + 0.5) / h - 1], -1).astype("float32") return torch.nn.functional.grid_sample( torch.from_numpy(f)[None], torch.from_numpy(grid)[None, None], mode="bilinear", padding_mode="border", align_corners=False, )[0, :, 0].T.numpy() def predict(f, size, indices, model, chunk=8192): result = np.empty(len(indices), dtype=bool) for lo in range(0, len(indices), chunk): x = feature_pixels(f, size, indices[lo : lo + chunk]) if model["head"] == "linear": m = model["parameters"] coef = np.asarray(m["coefficients"]) scaled = coef[1:] / np.asarray(m["scale"]) z = x @ scaled + coef[0] - np.asarray(m["mean"]) @ scaled else: z = mlp_logits(x, model["parameters"]) result[lo : lo + chunk] = z >= 0 return result def fit_candidate(units, candidate, held_out=None): if held_out is not None and any(u["group"] == held_out for u in units): raise ValueError("Held-out street entered fitting") if candidate["head"] == "linear": p = fit(units, candidate["l2"], 500) p["converged"] = True else: p = fit_mlp(units, hidden=32, seed=20261023, l2=candidate["l2"], max_iterations=500) return dict(candidate=candidate, head=candidate["head"], parameters=p) def setup(root): from dataset_store import checksum, read protocol = read(root / "protocol.json") frozen = read(root / "review-frozen.json") manifest = read(root / "feature-manifest.json") assert ( frozen["protocol_sha256"] == manifest["protocol_sha256"] == checksum(root / "protocol.json") ) assert frozen["source_sha256"] == checksum(Path(__file__)) assert frozen["supervision"] == manifest["supervision"] for name, sha in frozen["sources"].items(): assert checksum(root / name) == sha for r in manifest["records"]: assert checksum(root / r["cache"]) == r["sha256"] return protocol, manifest["records"] def development(root): import torch from dataset_store import checksum, write torch.set_num_threads(3) start = time.monotonic() protocol, records = setup(root) assert not (root / "development-selection.json").exists() units = {k: [] for k in ["semantic", "detail", "combined"]} for r in records: if r["split"] != "train": continue with np.load(root / r["cache"]) as z: for representation in units: units[representation].append( samples(features(z, representation), z["target"], r, protocol["fit"]) ) rows = [] (root / "models").mkdir(exist_ok=False) for fi, (held_out, learn, held) in enumerate(folds(records)): for candidate in protocol["candidates"]: started = time.monotonic() fitting = [u for u in units[candidate["representation"]] if u["group"] != held_out] assert {u["name"] for u in fitting} == {r["name"] for r in learn} model = fit_candidate(fitting, candidate, held_out) mp = root / "models" / ("fold" + str(fi) + "-" + candidate["id"] + ".json") write(mp, model) metrics = [] for r in held: with np.load(root / r["cache"]) as z: target = z["target"] indices = np.flatnonzero(target != 255) pred = predict( features(z, candidate["representation"]), target.shape, indices, model ) c = counts(pred, target.ravel()[indices]) c["ignored"] = int((target == 255).sum()) metrics.append(dict(name=r["name"], **c)) rows.append( dict( phase="development", candidate=candidate["id"], held_out=held_out, fitted_groups=model["parameters"]["training_groups"], model_path=mp.relative_to(root).as_posix(), model_sha256=checksum(mp), converged=model["parameters"]["converged"], iterations=model["parameters"]["iterations"], metrics=aggregate(metrics), windows=metrics, seconds=time.monotonic() - started, ) ) write( root / "development-progress.json", dict( completed=len(rows), total=4 * len(protocol["candidates"]), last=rows[-1], elapsed_seconds=time.monotonic() - start, ), ) choice = select_candidate(rows, protocol["baseline"]) write( root / "development-result.json", dict( rows=rows, selection=choice, seconds=time.monotonic() - start, protocol_sha256=checksum(root / "protocol.json"), source_sha256=checksum(Path(__file__)), ), ) write( root / "development-selection.json", dict( **choice, development_sha256=checksum(root / "development-result.json"), protocol_sha256=checksum(root / "protocol.json"), frozen_before_control_evaluation=True, ), ) print(json.dumps(choice)) def final_fit(root): import torch from dataset_store import checksum, read, write torch.set_num_threads(3) protocol, records = setup(root) choice = read(root / "development-selection.json") assert choice["development_sha256"] == checksum(root / "development-result.json") assert not (root / "models-frozen.json").exists() and not (root / "result.json").exists() selected = {protocol["baseline"], choice["selected"]} result = {} for candidate in protocol["candidates"]: if candidate["id"] not in selected: continue units = [] for r in records: if r["split"] != "train": continue with np.load(root / r["cache"]) as z: units.append( samples( features(z, candidate["representation"]), z["target"], r, protocol["fit"] ) ) result[candidate["id"]] = fit_candidate(units, candidate) assert result[candidate["id"]]["parameters"]["converged"] parent = read(Path("/store/experiments/semantic-nonlinear-20261023/models-frozen.json")) # Exact numeric baseline identity is checked against the previous fixed experiment. previous = parent["models"]["linear"] current = result[protocol["baseline"]]["parameters"] for key in ["mean", "scale", "coefficients"]: assert np.array_equal(current[key], previous[key]), key write( root / "models-frozen.json", dict( models=result, selection_sha256=checksum(root / "development-selection.json"), protocol_sha256=checksum(root / "protocol.json"), baseline_exactly_reproduced=True, production_eligible=False, frozen_before_controls=True, ), ) print(json.dumps({"fitted": sorted(result), "baseline_exactly_reproduced": True})) def control_evaluation(root): import torch from admission_store import pixel_target from dataset_store import checksum, read, write torch.set_num_threads(3) protocol, records = setup(root) choice = read(root / "development-selection.json") frozen = read(root / "models-frozen.json") assert frozen["selection_sha256"] == checksum(root / "development-selection.json") assert not (root / "result.json").exists() rows = [] audit = {} for r in records: if r["split"] != "regression": continue with np.load(root / r["cache"]) as z: target = z["target"] predictions = {} for key, model in frozen["models"].items(): pred = predict( features(z, model["candidate"]["representation"]), target.shape, np.arange(target.size), model, ).reshape(target.shape) predictions[key] = pred rows.append( dict(name=r["name"], group=r["group"], candidate=key, **counts(pred, target)) ) if r["name"] == "P1": runs = read(root / "p1-audit-runs-final.json") from admission_store import pixel_target t = np.frombuffer( pixel_target(dict(runs, size=[target.shape[1], target.shape[0]])), dtype="uint8", ).reshape(target.shape) audit[key] = aggregate([counts(pred, t)]) np.savez_compressed(root / "cache" / (r["name"] + "-predictions.npz"), **predictions) metrics = { g: { c: aggregate([r for r in rows if r["group"] == g and r["candidate"] == c]) for c in frozen["models"] } for g in sorted({r["group"] for r in rows}) } b, s = protocol["baseline"], choice["selected"] failures = [] for g, mm in metrics.items(): for key, sign in [("recall", 1), ("fpr", -1)]: if mm[b][key] is not None and sign * (mm[s][key] - mm[b][key]) < -1e-12: failures.append(g + ": " + key) if audit[s]["recall"] < audit[b]["recall"] or audit[s]["fpr"] >= audit[b]["fpr"]: failures.append("P1 diagnostic recall/gap gate") if s == b: failures.append("No development improvement selected") write( root / "result.json", dict( rows=rows, metrics=metrics, p1_diagnostic=audit, selection=choice, qualification=dict(accepted=not failures, failures=failures, production_eligible=False), protocol_sha256=checksum(root / "protocol.json"), source_sha256=checksum(Path(__file__)), models_sha256=checksum(root / "models-frozen.json"), control_selection=False, ), ) print(json.dumps({"metrics": metrics, "audit": audit, "failures": failures})) if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("phase", choices=["development", "fit", "evaluate"]) ap.add_argument("--root", type=Path, default=Path("/experiment")) args = ap.parse_args() {"development": development, "fit": final_fit, "evaluate": control_evaluation}[args.phase]( args.root )