feat(semantics): add portable annotation, learning and review contracts
Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
This commit is contained in:
@@ -0,0 +1,195 @@
|
||||
"""Bounded train-only sample-growth experiment with frozen exposed controls."""
|
||||
|
||||
import argparse
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from pixel_growth_probe import aggregate, counts, fit, resize_plane
|
||||
from scipy.special import expit
|
||||
from supervision_density_probe import check_pair, load_examples, samples
|
||||
|
||||
|
||||
def check_expansion(old, new, before, after):
|
||||
if not set(old) < set(new):
|
||||
raise ValueError("Expected a strict sample expansion")
|
||||
groups = {e["physical_group"] for e in old.values() if e["split"] == "train"}
|
||||
seen_images = {i["rgb"]["sha256"] for e in old.values() for i in e["inputs"]}
|
||||
for sid, e in old.items():
|
||||
check_pair(e, new[sid], before[sid], after[sid])
|
||||
if not np.array_equal(before[sid], after[sid]):
|
||||
raise ValueError("Existing training targets changed")
|
||||
for sid in set(new) - set(old):
|
||||
e = new[sid]
|
||||
if e["split"] != "train" or e["physical_group"] not in groups:
|
||||
raise ValueError("Addition must belong to an existing training physical group")
|
||||
if not {0, 1} <= set(np.unique(after[sid])):
|
||||
raise ValueError("New crossing requires both paint and gap background")
|
||||
for i in e["inputs"]:
|
||||
if i["rgb"]["sha256"] in seen_images:
|
||||
raise ValueError("Duplicate observation in added windows")
|
||||
seen_images.add(i["rgb"]["sha256"])
|
||||
|
||||
|
||||
def qualify(metrics, audit, reproduced):
|
||||
failures = []
|
||||
if not reproduced:
|
||||
failures.append("baseline reproduction failed")
|
||||
for group, variants in metrics.items():
|
||||
for metric, sign in [("recall", 1), ("fpr", -1)]:
|
||||
a, b = variants["baseline"][metric], variants["expanded"][metric]
|
||||
if a is not None and b is not None and sign * (b - a) < -1e-12:
|
||||
failures.append(group + ": " + metric)
|
||||
if audit["expanded"]["recall"] < audit["baseline"]["recall"]:
|
||||
failures.append("diagnostic paint recall")
|
||||
if audit["expanded"]["fpr"] >= audit["baseline"]["fpr"]:
|
||||
failures.append("diagnostic gap false positives not strictly reduced")
|
||||
return dict(accepted=not failures, failures=failures)
|
||||
|
||||
|
||||
def run(root, store):
|
||||
import torch
|
||||
from admission_store import pixel_target
|
||||
from dataset_store import checksum, read, write
|
||||
|
||||
torch.set_num_threads(3)
|
||||
start = time.monotonic()
|
||||
assert not (root / "models-frozen.json").exists() and not (root / "result.json").exists()
|
||||
protocol = read(root / "protocol.json")
|
||||
frozen = read(root / "review-frozen.json")
|
||||
manifest = read(root / "feature-manifest.json")
|
||||
parent = store / "experiments" / protocol["parent"]
|
||||
assert frozen["source_sha256"] == checksum(Path(__file__))
|
||||
assert (
|
||||
manifest["protocol_sha256"] == frozen["protocol_sha256"] == checksum(root / "protocol.json")
|
||||
)
|
||||
for key, name in [
|
||||
("audit_sha256", "p1-audit-runs-final.json"),
|
||||
("pixel_runs_sha256", "pixel-runs-final.json"),
|
||||
("regions_sha256", "regions-final.json"),
|
||||
]:
|
||||
assert frozen[key] == checksum(root / name)
|
||||
assert checksum(root / "model-inventory.json") == checksum(parent / "model-inventory.json")
|
||||
params = protocol["fit"]
|
||||
assert params == read(parent / "protocol.json")["fit"]
|
||||
old_receipt = read(parent / "supervision-receipt.json")
|
||||
assert old_receipt["sha256"] == protocol["parent_release_sha256"]
|
||||
old, before = load_examples(store, old_receipt)
|
||||
new, after = load_examples(store, read(root / "supervision-receipt.json"))
|
||||
check_expansion(old, new, before, after)
|
||||
assert set(new) == {r["sample_id"] for r in manifest["records"]}
|
||||
assert {r["name"] for r in manifest["records"] if r["sample_id"] not in old} == set(
|
||||
protocol["added_training_windows"]
|
||||
)
|
||||
units = {"baseline": [], "expanded": []}
|
||||
for r in manifest["records"]:
|
||||
sid = r["sample_id"]
|
||||
assert checksum(root / r["cache"]) == r["sha256"]
|
||||
with np.load(root / r["cache"]) as z:
|
||||
assert np.array_equal(z["target"], after[sid])
|
||||
if r["split"] == "train":
|
||||
unit = samples(z["features"].astype("float32"), after[sid], r, params)
|
||||
units["expanded"].append(unit)
|
||||
if sid in old:
|
||||
units["baseline"].append(unit)
|
||||
models = {arm: fit(us, params["l2"], params["max_iterations"]) for arm, us in units.items()}
|
||||
fit_seconds = time.monotonic() - start
|
||||
write(
|
||||
root / "models-frozen.json",
|
||||
dict(
|
||||
models=models,
|
||||
threshold=params["threshold"],
|
||||
protocol_sha256=checksum(root / "protocol.json"),
|
||||
review_sha256=checksum(root / "review-frozen.json"),
|
||||
features_sha256=checksum(root / "feature-manifest.json"),
|
||||
source_sha256=checksum(Path(__file__)),
|
||||
frozen_before_evaluation=True,
|
||||
),
|
||||
)
|
||||
rows, train_rows, diagnostic = [], [], None
|
||||
old_rows = {r["name"]: r for r in read(parent / "result.json")["rows"]}
|
||||
for r in manifest["records"]:
|
||||
# Training diagnostics are reported separately, never scored as transfer.
|
||||
with np.load(root / r["cache"]) as z:
|
||||
features, target = z["features"].astype("float32"), z["target"]
|
||||
predictions = {}
|
||||
for arm, m in models.items():
|
||||
coef = np.array(m["coefficients"])
|
||||
scaled = coef[1:] / np.array(m["scale"])
|
||||
bias = coef[0] - np.array(m["mean"]) @ scaled
|
||||
logits = np.einsum("chw,c->hw", features, scaled) + bias
|
||||
predictions[arm] = (
|
||||
expit(resize_plane(logits[None], target.shape)[0]) >= params["threshold"]
|
||||
)
|
||||
np.savez_compressed(root / "cache" / (r["name"] + "-predictions.npz"), **predictions)
|
||||
row = dict(
|
||||
name=r["name"],
|
||||
group=r["group"],
|
||||
variants={arm: counts(p, target) for arm, p in predictions.items()},
|
||||
)
|
||||
(rows if r["split"] == "regression" else train_rows).append(row)
|
||||
if r["name"] == "P1":
|
||||
t = read(root / "p1-audit-runs-final.json")
|
||||
audit_target = np.frombuffer(
|
||||
pixel_target(dict(t, size=[512, 512])), dtype="uint8"
|
||||
).reshape(512, 512)
|
||||
diagnostic = {
|
||||
arm: aggregate([counts(p, audit_target)]) for arm, p in predictions.items()
|
||||
}
|
||||
assert diagnostic is not None
|
||||
metrics = {
|
||||
g: {arm: aggregate([r["variants"][arm] for r in rows if r["group"] == g]) for arm in models}
|
||||
for g in sorted({r["group"] for r in rows})
|
||||
}
|
||||
reproduced_counts = all(
|
||||
r["variants"]["baseline"] == old_rows[r["name"]]["variants"]["dense"] for r in rows
|
||||
)
|
||||
prior_model = read(parent / "models-frozen.json")["models"]["dense"]
|
||||
delta = max(
|
||||
float(np.max(np.abs(np.array(models["baseline"][k]) - np.array(prior_model[k]))))
|
||||
for k in ["mean", "scale", "coefficients"]
|
||||
)
|
||||
outcome = qualify(metrics, diagnostic, reproduced_counts and delta == 0.0)
|
||||
result = dict(
|
||||
**outcome,
|
||||
metrics=metrics,
|
||||
rows=rows,
|
||||
train_rows=train_rows,
|
||||
diagnostic=diagnostic,
|
||||
baseline_reproduced=reproduced_counts and delta == 0.0,
|
||||
baseline_max_parameter_delta=delta,
|
||||
models_sha256=checksum(root / "models-frozen.json"),
|
||||
source_sha256=checksum(Path(__file__)),
|
||||
protocol_sha256=checksum(root / "protocol.json"),
|
||||
fit_and_load_seconds=fit_seconds,
|
||||
total_seconds=time.monotonic() - start,
|
||||
evaluated_utc=__import__("datetime")
|
||||
.datetime.now(__import__("datetime").timezone.utc)
|
||||
.isoformat(),
|
||||
production_eligible=False,
|
||||
blind_generalization_claim=False,
|
||||
)
|
||||
write(root / "result.json", result)
|
||||
print(
|
||||
__import__("json").dumps(
|
||||
{
|
||||
k: result[k]
|
||||
for k in [
|
||||
"accepted",
|
||||
"failures",
|
||||
"metrics",
|
||||
"diagnostic",
|
||||
"baseline_reproduced",
|
||||
"baseline_max_parameter_delta",
|
||||
]
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("root", type=Path)
|
||||
parser.add_argument("--store", type=Path, default=Path("/store"))
|
||||
args = parser.parse_args()
|
||||
run(args.root, args.store)
|
||||
Reference in New Issue
Block a user