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,363 @@
|
||||
"""Offline fixed-recipe pixel growth probe; explicit admitted pixels only.
|
||||
|
||||
Frozen visual features, training-only normalization and class/area/window balance.
|
||||
No source identities or coordinates enter inference. No production publication.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from scipy.optimize import minimize
|
||||
from scipy.special import expit
|
||||
|
||||
|
||||
def balanced_weights(units):
|
||||
"""Each class has half the mass; areas then windows share that mass equally."""
|
||||
if set(np.concatenate([u["y"] for u in units])) != {0, 1}:
|
||||
raise ValueError("Both reviewed classes are required")
|
||||
weights = [np.zeros(len(u["y"])) for u in units]
|
||||
for label in [0, 1]:
|
||||
groups = sorted({u["group"] for u in units if np.any(u["y"] == label)})
|
||||
for group in groups:
|
||||
indices = [
|
||||
i for i, u in enumerate(units) if u["group"] == group and np.any(u["y"] == label)
|
||||
]
|
||||
for i in indices:
|
||||
m = units[i]["y"] == label
|
||||
weights[i][m] = 0.5 / len(groups) / len(indices) / m.sum()
|
||||
return np.concatenate(weights)
|
||||
|
||||
|
||||
def fit(units, l2=0.01, max_iterations=500):
|
||||
if any(u["split"] != "train" for u in units):
|
||||
raise ValueError("Only training units may fit the classifier")
|
||||
x = np.concatenate([u["x"] for u in units]).astype(float)
|
||||
y = np.concatenate([u["y"] for u in units])
|
||||
if not np.isfinite(x).all() or x.ndim != 2 or len(x) != len(y):
|
||||
raise ValueError("Invalid feature samples")
|
||||
weight = balanced_weights(units)
|
||||
mean = (x * weight[:, None]).sum(0)
|
||||
scale = np.maximum(np.sqrt(((x - mean) ** 2 * weight[:, None]).sum(0)), 1e-5)
|
||||
design = np.column_stack([np.ones(len(x)), (x - mean) / scale])
|
||||
|
||||
def objective(w):
|
||||
z = design @ w
|
||||
loss = np.sum(weight * (np.logaddexp(0, z) - y * z)) + l2 * np.sum(w[1:] ** 2) / 2
|
||||
grad = design.T @ (weight * (expit(z) - y))
|
||||
grad[1:] += l2 * w[1:]
|
||||
return loss, grad
|
||||
|
||||
result = minimize(
|
||||
objective,
|
||||
np.zeros(design.shape[1]),
|
||||
jac=True,
|
||||
method="L-BFGS-B",
|
||||
options={"maxiter": max_iterations},
|
||||
)
|
||||
if not result.success:
|
||||
raise RuntimeError("Fit did not converge: " + str(result.message))
|
||||
return dict(
|
||||
mean=mean.tolist(),
|
||||
scale=scale.tolist(),
|
||||
coefficients=result.x.tolist(),
|
||||
iterations=int(result.nit),
|
||||
samples=len(y),
|
||||
training_groups=sorted({u["group"] for u in units}),
|
||||
production_eligible=False,
|
||||
)
|
||||
|
||||
|
||||
def counts(pred, target):
|
||||
pred = np.asarray(pred, dtype=bool)
|
||||
target = np.asarray(target)
|
||||
if pred.shape != target.shape or not set(np.unique(target)) <= {0, 1, 255}:
|
||||
raise ValueError("Target shape or label contract violated")
|
||||
return dict(
|
||||
tp=int((pred & (target == 1)).sum()),
|
||||
fn=int((~pred & (target == 1)).sum()),
|
||||
fp=int((pred & (target == 0)).sum()),
|
||||
tn=int((~pred & (target == 0)).sum()),
|
||||
ignored=int((target == 255).sum()),
|
||||
)
|
||||
|
||||
|
||||
def aggregate(rows):
|
||||
c = {k: sum(r[k] for r in rows) for k in ["tp", "fn", "fp", "tn", "ignored"]}
|
||||
c["recall"] = c["tp"] / (c["tp"] + c["fn"]) if c["tp"] + c["fn"] else None
|
||||
c["fpr"] = c["fp"] / (c["fp"] + c["tn"]) if c["fp"] + c["tn"] else None
|
||||
return c
|
||||
|
||||
|
||||
def resize_plane(a, size):
|
||||
import torch
|
||||
|
||||
return torch.nn.functional.interpolate(
|
||||
torch.from_numpy(a.astype("float32"))[None], size=size, mode="bilinear", align_corners=False
|
||||
)[0].numpy()
|
||||
|
||||
|
||||
def extract(root, store):
|
||||
import torch
|
||||
from admission_store import Supervision, pixel_target
|
||||
from dataset_store import checksum, read, write
|
||||
from PIL import Image
|
||||
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
|
||||
|
||||
torch.set_num_threads(3)
|
||||
receipt = read(root / "supervision-receipt.json")
|
||||
frozen = read(root / "review-frozen.json")
|
||||
assert frozen["supervision"] == receipt and frozen["protocol_sha256"] == checksum(
|
||||
root / "protocol.json"
|
||||
)
|
||||
inventory = {
|
||||
p.name: dict(sha256=checksum(p), bytes=p.stat().st_size)
|
||||
for p in Path("/model").iterdir()
|
||||
if p.is_file() and p.suffix in [".json", ".safetensors", ".bin"]
|
||||
}
|
||||
write(root / "model-inventory.json", inventory)
|
||||
processor = AutoImageProcessor.from_pretrained("/model", local_files_only=True)
|
||||
model = (
|
||||
Mask2FormerForUniversalSegmentation.from_pretrained("/model", local_files_only=True)
|
||||
.eval()
|
||||
.to("cuda")
|
||||
)
|
||||
for p in model.parameters():
|
||||
p.requires_grad_(False)
|
||||
assert (
|
||||
model.config.id2label[23] == "Lane Marking - Crosswalk"
|
||||
and model.config.id2label[24] == "Lane Marking - General"
|
||||
)
|
||||
cache = root / "cache"
|
||||
cache.mkdir(exist_ok=False)
|
||||
refs = read(root / "selected-references.json")
|
||||
names = {r["id"]: n for n, r in refs.items()}
|
||||
records = []
|
||||
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]
|
||||
desc = next(
|
||||
v
|
||||
for v in e["inputs"]
|
||||
if v["view"] == t["view"] and v["sample_id"] == e["sample_id"]
|
||||
)
|
||||
with reader.open_image(desc) as stream:
|
||||
im = Image.open(stream)
|
||||
im.load()
|
||||
im = im.convert("RGB")
|
||||
assert list(im.size) == t["size"]
|
||||
rgb = np.asarray(im.resize((512, 512), Image.Resampling.BICUBIC))
|
||||
features = []
|
||||
semantic = []
|
||||
for k in range(4):
|
||||
tensors = processor(
|
||||
images=Image.fromarray(np.rot90(rgb, k).copy()),
|
||||
return_tensors="pt",
|
||||
size={"height": 512, "width": 512},
|
||||
).to("cuda")
|
||||
assert tuple(tensors["pixel_values"].shape[-2:]) == (512, 512)
|
||||
with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16):
|
||||
out = model(**tensors, output_hidden_states=True)
|
||||
f = torch.rot90(out.pixel_decoder_last_hidden_state[0].float(), -k, [-2, -1])
|
||||
assert tuple(f.shape) == (256, 128, 128)
|
||||
sem = torch.einsum(
|
||||
"qc,qhw->chw",
|
||||
out.class_queries_logits[0].float().softmax(-1)[:, :-1],
|
||||
out.masks_queries_logits[0].float().sigmoid(),
|
||||
)
|
||||
sem = torch.rot90(sem, -k, [-2, -1])
|
||||
features.append(f.cpu().numpy())
|
||||
semantic.append(sem.cpu().numpy())
|
||||
del out, tensors, f, sem
|
||||
n = names[e["sample_id"]]
|
||||
path = cache / (n + ".npz")
|
||||
target = np.frombuffer(pixel_target(t), dtype=np.uint8).reshape(im.height, im.width)
|
||||
np.savez_compressed(
|
||||
path,
|
||||
features=np.mean(features, axis=0).astype("float16"),
|
||||
semantic=np.mean(semantic, axis=0).astype("float16"),
|
||||
target=target,
|
||||
)
|
||||
records.append(
|
||||
dict(
|
||||
name=n,
|
||||
sample_id=e["sample_id"],
|
||||
group=e["physical_group"],
|
||||
split=split,
|
||||
cache=path.relative_to(root).as_posix(),
|
||||
sha256=checksum(path),
|
||||
input=desc,
|
||||
target_sha256=hashlib.sha256(target.tobytes()).hexdigest(),
|
||||
size=list(im.size),
|
||||
)
|
||||
)
|
||||
assert len(records) <= 32
|
||||
print("extracted " + n, flush=True)
|
||||
write(
|
||||
root / "feature-manifest.json",
|
||||
dict(
|
||||
records=records,
|
||||
model_inventory_sha256=checksum(root / "model-inventory.json"),
|
||||
supervision=receipt,
|
||||
script_sha256=checksum(Path(__file__)),
|
||||
protocol_sha256=checksum(root / "protocol.json"),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def fit_and_evaluate(root):
|
||||
import torch
|
||||
from dataset_store import checksum, read, write
|
||||
|
||||
torch.set_num_threads(3)
|
||||
manifest = read(root / "feature-manifest.json")
|
||||
protocol = read(root / "protocol.json")
|
||||
params = protocol["fit"]
|
||||
plan = read(root / "experiment-plan.json")
|
||||
assert checksum(root / "protocol.json") == manifest["protocol_sha256"]
|
||||
assert not (root / "models-frozen.json").exists() and not (root / "result.json").exists()
|
||||
units = []
|
||||
for r in manifest["records"]:
|
||||
assert checksum(root / r["cache"]) == r["sha256"]
|
||||
if r["split"] != "train":
|
||||
continue
|
||||
with np.load(root / r["cache"]) as z:
|
||||
target = z["target"]
|
||||
f = z["features"].astype("float32")
|
||||
h, w = target.shape
|
||||
rng = np.random.default_rng(params["seed"] + int(r["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(f)[None],
|
||||
torch.from_numpy(grid)[None, None],
|
||||
mode="bilinear",
|
||||
padding_mode="border",
|
||||
align_corners=False,
|
||||
)[0, :, 0].T.numpy()
|
||||
units.append(
|
||||
dict(
|
||||
name=r["name"],
|
||||
group=r["group"],
|
||||
split=r["split"],
|
||||
x=x,
|
||||
y=target.ravel()[chosen],
|
||||
)
|
||||
)
|
||||
models = {}
|
||||
for arm, groups in plan["arms"].items():
|
||||
selected = [u for u in units if u["group"] in groups]
|
||||
assert {u["group"] for u in selected} == set(groups)
|
||||
models[arm] = fit(selected, params["l2"], params["max_iterations"])
|
||||
write(
|
||||
root / "models-frozen.json",
|
||||
dict(
|
||||
models=models,
|
||||
features_sha256=checksum(root / "feature-manifest.json"),
|
||||
review_sha256=checksum(root / "review-frozen.json"),
|
||||
threshold=params["threshold"],
|
||||
protocol_sha256=checksum(root / "protocol.json"),
|
||||
),
|
||||
)
|
||||
# Both heads are immutable before any control metric or prediction is examined.
|
||||
results = []
|
||||
for r in manifest["records"]:
|
||||
if r["split"] != "regression":
|
||||
continue
|
||||
with np.load(root / r["cache"]) as z:
|
||||
f = z["features"].astype("float32")
|
||||
target = z["target"]
|
||||
sem = resize_plane(z["semantic"], target.shape)
|
||||
preds = {"pretrained": np.isin(sem.argmax(0), [23, 24])}
|
||||
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", f, scaled) + bias
|
||||
preds[arm] = (
|
||||
expit(resize_plane(logits[None], target.shape)[0]) >= params["threshold"]
|
||||
)
|
||||
np.savez_compressed(root / "cache" / (r["name"] + "-predictions.npz"), **preds)
|
||||
results.append(
|
||||
dict(
|
||||
name=r["name"],
|
||||
group=r["group"],
|
||||
scope="reviewed-road-roi"
|
||||
if r["name"] in plan["complete_roi_names"]
|
||||
else "explicit-reviewed-probes",
|
||||
variants={arm: counts(pred, target) for arm, pred in preds.items()},
|
||||
)
|
||||
)
|
||||
groups = sorted({r["group"] for r in results})
|
||||
metrics = {
|
||||
g: {
|
||||
arm: aggregate([r["variants"][arm] for r in results if r["group"] == g])
|
||||
for arm in ["pretrained", "single", "expanded"]
|
||||
}
|
||||
for g in groups
|
||||
}
|
||||
failures = []
|
||||
gains = []
|
||||
for g, m in metrics.items():
|
||||
for metric, sign in [("recall", 1), ("fpr", -1)]:
|
||||
a = m["single"][metric]
|
||||
b = m["expanded"][metric]
|
||||
if a is None or b is None:
|
||||
continue
|
||||
if sign * (b - a) < -1e-12:
|
||||
failures.append(dict(group=g, metric=metric, single=a, expanded=b))
|
||||
if sign * (b - a) > 1e-12:
|
||||
gains.append(dict(group=g, metric=metric, single=a, expanded=b))
|
||||
write(
|
||||
root / "result.json",
|
||||
dict(
|
||||
metrics=metrics,
|
||||
rows=results,
|
||||
accepted=not failures and bool(gains),
|
||||
failures=failures,
|
||||
gains=gains,
|
||||
models_sha256=checksum(root / "models-frozen.json"),
|
||||
production_eligible=False,
|
||||
blind_generalization_claim=False,
|
||||
protocol_sha256=checksum(root / "protocol.json"),
|
||||
evaluated_utc=__import__("datetime")
|
||||
.datetime.now(__import__("datetime").timezone.utc)
|
||||
.isoformat(),
|
||||
),
|
||||
)
|
||||
print(
|
||||
json.dumps(dict(metrics=metrics, accepted=not failures and bool(gains), failures=failures)),
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("phase", choices=["extract", "fit"])
|
||||
p.add_argument("root", type=Path)
|
||||
p.add_argument("--store", type=Path, default=Path("/store"))
|
||||
args = p.parse_args()
|
||||
start = time.monotonic()
|
||||
(extract(args.root, args.store) if args.phase == "extract" else fit_and_evaluate(args.root))
|
||||
print("seconds", round(time.monotonic() - start, 2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user