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,234 @@
|
||||
"""Offline paired review-coverage experiment over frozen visual features."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
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
|
||||
|
||||
|
||||
def check_pair(sparse, dense, before, after):
|
||||
for field in ["sample_id", "source", "physical_group", "split", "inputs"]:
|
||||
if sparse[field] != dense[field]:
|
||||
raise ValueError("Changed paired input: " + field)
|
||||
if before.shape != after.shape or not set(np.unique(after)) <= {0, 1, 255}:
|
||||
raise ValueError("Invalid dense target")
|
||||
known = before != 255
|
||||
if not np.array_equal(before[known], after[known]):
|
||||
raise ValueError("Existing reviewed labels changed")
|
||||
if sparse["split"] != "train" and not np.array_equal(before, after):
|
||||
raise ValueError("Original control target changed")
|
||||
|
||||
|
||||
def qualify(metrics, audit, reproduced):
|
||||
failures, gains = [], []
|
||||
if not reproduced:
|
||||
failures.append("sparse baseline did not reproduce prior control counts")
|
||||
for group, variants in metrics.items():
|
||||
for metric, sign in [("recall", 1), ("fpr", -1)]:
|
||||
a, b = variants["sparse"][metric], variants["dense"][metric]
|
||||
if a is None or b is None:
|
||||
continue
|
||||
if sign * (b - a) < -1e-12:
|
||||
failures.append(group + ": " + metric)
|
||||
if sign * (b - a) > 1e-12:
|
||||
gains.append(group + ": " + metric)
|
||||
if audit["dense"]["recall"] < audit["sparse"]["recall"]:
|
||||
failures.append("diagnostic paint recall")
|
||||
if audit["dense"]["fpr"] >= audit["sparse"]["fpr"]:
|
||||
failures.append("diagnostic gap false positives not strictly reduced")
|
||||
if not gains:
|
||||
failures.append("no strict gain on original regression")
|
||||
return dict(accepted=not failures, failures=failures, gains=gains)
|
||||
|
||||
|
||||
def load_examples(store, receipt):
|
||||
from admission_store import Supervision, pixel_target
|
||||
|
||||
examples, targets = {}, {}
|
||||
with Supervision(store, receipt["path"], receipt["sha256"]) as reader:
|
||||
for split in ["train", "regression"]:
|
||||
for batch in reader.batches("observed_paint", split, batch_size=1):
|
||||
e = batch[0]
|
||||
assert len(e["targets"]) == 1
|
||||
t = e["targets"][0]
|
||||
examples[e["sample_id"]] = e
|
||||
targets[e["sample_id"]] = np.frombuffer(pixel_target(t), dtype="uint8").reshape(
|
||||
t["size"][1], t["size"][0]
|
||||
)
|
||||
return examples, targets
|
||||
|
||||
|
||||
def samples(features, target, record, params):
|
||||
if record["split"] != "train":
|
||||
raise ValueError("Only train records may provide fitting samples")
|
||||
import torch
|
||||
h, w = target.shape
|
||||
rng = np.random.default_rng(params["seed"] + int(record["sample_id"][:8], 16))
|
||||
chosen = []
|
||||
for label in [0, 1]:
|
||||
indices = np.flatnonzero(target == label)
|
||||
chosen.extend(
|
||||
rng.choice(
|
||||
indices,
|
||||
min(len(indices), params["max_samples_per_class_per_window"]),
|
||||
replace=False,
|
||||
)
|
||||
)
|
||||
chosen = np.asarray(chosen)
|
||||
ys, xs = np.unravel_index(chosen, (h, w))
|
||||
grid = np.stack([2 * (xs + 0.5) / w - 1, 2 * (ys + 0.5) / h - 1], -1).astype("float32")
|
||||
x = torch.nn.functional.grid_sample(
|
||||
torch.from_numpy(features)[None],
|
||||
torch.from_numpy(grid)[None, None],
|
||||
mode="bilinear",
|
||||
padding_mode="border",
|
||||
align_corners=False,
|
||||
)[0, :, 0].T.numpy()
|
||||
return dict(
|
||||
name=record["name"], group=record["group"], split="train", x=x, y=target.ravel()[chosen]
|
||||
)
|
||||
|
||||
|
||||
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")
|
||||
)
|
||||
assert frozen["audit_sha256"] == checksum(root / "p1-audit-runs-final.json")
|
||||
assert frozen["pixel_runs_sha256"] == checksum(root / "pixel-runs-final.json")
|
||||
assert frozen["regions_sha256"] == checksum(root / "regions-final.json")
|
||||
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"))
|
||||
assert set(old) == set(new) == {r["sample_id"] for r in manifest["records"]}
|
||||
units = {"sparse": [], "dense": []}
|
||||
for r in manifest["records"]:
|
||||
sid = r["sample_id"]
|
||||
check_pair(old[sid], new[sid], before[sid], after[sid])
|
||||
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":
|
||||
for arm, target in [("sparse", before[sid]), ("dense", after[sid])]:
|
||||
units[arm].append(samples(z["features"].astype("float32"), target, r, params))
|
||||
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 = []
|
||||
diagnostic = None
|
||||
old_rows = {r["name"]: r for r in read(parent / "result.json")["rows"]}
|
||||
for r in manifest["records"]:
|
||||
if r["split"] != "regression":
|
||||
continue
|
||||
with np.load(root / r["cache"]) as z:
|
||||
features = z["features"].astype("float32")
|
||||
target = 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)
|
||||
rows.append(
|
||||
dict(
|
||||
name=r["name"],
|
||||
group=r["group"],
|
||||
variants={arm: counts(p, target) for arm, p in predictions.items()},
|
||||
)
|
||||
)
|
||||
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 = all(
|
||||
r["variants"]["sparse"] == old_rows[r["name"]]["variants"]["expanded"] for r in rows
|
||||
)
|
||||
prior_model = read(parent / "models-frozen.json")["models"]["expanded"]
|
||||
delta = max(
|
||||
float(np.max(np.abs(np.array(models["sparse"][k]) - np.array(prior_model[k]))))
|
||||
for k in ["mean", "scale", "coefficients"]
|
||||
)
|
||||
outcome = qualify(metrics, diagnostic, reproduced)
|
||||
write(
|
||||
root / "result.json",
|
||||
dict(
|
||||
**outcome,
|
||||
metrics=metrics,
|
||||
rows=rows,
|
||||
diagnostic=diagnostic,
|
||||
sparse_reproduced=reproduced,
|
||||
sparse_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,
|
||||
),
|
||||
)
|
||||
print(
|
||||
json.dumps(
|
||||
dict(
|
||||
**outcome,
|
||||
metrics=metrics,
|
||||
diagnostic=diagnostic,
|
||||
sparse_reproduced=reproduced,
|
||||
parameter_delta=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