Files
DCCONSTRUCTIONS 25dc0a1b44 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.
2026-10-29 09:10:00 +03:00

496 lines
18 KiB
Python

"""Frozen-data, grouped comparison of label coverage and learned spatial residuals.
A 1x1 residual is an optimizer/capacity control for the 3x3 spatial head.
No street coordinates or manual geometry enters inference. No deployment.
"""
import argparse
import json
import os
import time
from pathlib import Path
import numpy as np
from pixel_growth_probe import aggregate, counts, fit, resize_plane
from street_holdout_probe import folds
from supervision_density_probe import samples
def dense_weights(records):
if any(r["split"] != "train" for r in records):
raise ValueError("Only training records may define loss weights")
weights = {r["name"]: np.zeros(r["target"].shape, dtype="float32") for r in records}
for label in (0, 1):
groups = sorted({r["group"] for r in records if np.any(r["target"] == label)})
if not groups:
raise ValueError("Both reviewed classes required")
for group in groups:
present = [r for r in records if r["group"] == group and np.any(r["target"] == label)]
for r in present:
mask = r["target"] == label
weights[r["name"]][mask] = 0.5 / len(groups) / len(present) / mask.sum()
return weights
def choose(rows):
"""Each predefined seed must pass mean/worst-street gates; never select a seed."""
if any(r["phase"] != "development" for r in rows):
raise ValueError("Development only")
groups = {r["held_out"] for r in rows}
if len(groups) != 4:
raise ValueError("Four complete physical-street folds required")
arms = sorted({r["arm"] for r in rows})
summary = {}
for arm in arms:
rr = [r for r in rows if r["arm"] == arm]
if len(rr) != 4 or {r["held_out"] for r in rr} != groups:
raise ValueError("Incomplete arm")
ber = [(1 - r["metrics"]["recall"] + r["metrics"]["fpr"]) / 2 for r in rr]
summary[arm] = dict(
mean=float(np.mean(ber)), worst=max(ber), completed=all(r["completed"] for r in rr)
)
base = summary["old-linear"]
eligible = []
families = {
"new-linear": ["new-linear"],
**{
f: [f + "-" + str(s) for s in [20261023, 20261024, 20261025]]
for f in ["pointwise", "spatial"]
},
}
for family, members in families.items():
if all(
summary[a]["completed"]
and summary[a]["mean"] < base["mean"] - 1e-12
and summary[a]["worst"] <= base["worst"] + 1e-12
for a in members
):
eligible.append(family)
selected = (
min(
eligible,
key=lambda f: (
max(summary[a]["mean"] for a in families[f]),
max(summary[a]["worst"] for a in families[f]),
f,
),
)
if eligible
else "old-linear"
)
return dict(
selected_family=selected,
selected_arms=families.get(selected, ["old-linear"]),
summaries=summary,
eligible_families=eligible,
all_seeds_required=True,
frozen_before_controls=True,
)
def network(base, kernel, seed):
import torch
from torch import nn
if kernel not in (1, 3):
raise ValueError("Only preregistered kernels")
torch.manual_seed(seed)
class Residual(nn.Module):
def __init__(self):
super().__init__()
self.register_buffer(
"coef",
torch.tensor(base["coefficients"][1:], dtype=torch.float32)[None, :, None, None],
)
self.register_buffer("bias", torch.tensor(base["coefficients"][0], dtype=torch.float32))
self.layers = nn.Sequential(
nn.Conv2d(256, 16, 1),
nn.Tanh(),
nn.Conv2d(16, 16, kernel, padding=kernel // 2, padding_mode="replicate"),
nn.Tanh(),
nn.Conv2d(16, 1, 1),
)
nn.init.zeros_(self.layers[-1].weight)
nn.init.zeros_(self.layers[-1].bias)
def forward(self, x):
return (x * self.coef).sum(1, keepdim=True) + self.bias + self.layers(x)
return Residual()
def linear_prediction(record, model):
c = np.asarray(model["coefficients"])
scaled = c[1:] / np.asarray(model["scale"])
logits = (
np.einsum("chw,c->hw", record["features"], scaled)
+ c[0]
- np.asarray(model["mean"]) @ scaled
)
return resize_plane(logits[None], record["target"].shape)[0] >= 0
def residual_prediction(record, model, base, device):
import torch
f = torch.from_numpy(record["features"]).to(device)[None]
mean = torch.tensor(base["mean"], device=device, dtype=torch.float32)[None, :, None, None]
scale = torch.tensor(base["scale"], device=device, dtype=torch.float32)[None, :, None, None]
with torch.inference_mode():
logits = torch.nn.functional.interpolate(
model((f - mean) / scale),
size=record["target"].shape,
mode="bilinear",
align_corners=False,
)
return (logits[0, 0] >= 0).cpu().numpy()
def fit_residual(records, base, kernel, seed, root, tag, steps):
import torch
from dataset_store import write
start = time.monotonic()
weights = dense_weights(records)
device = "cuda"
net = network(base, kernel, seed).to(device)
mean = torch.tensor(base["mean"], device=device, dtype=torch.float32)[None, :, None, None]
scale = torch.tensor(base["scale"], device=device, dtype=torch.float32)[None, :, None, None]
batch = []
for r in records:
f = (torch.from_numpy(r["features"]).to(device)[None] - mean) / scale
known = r["target"] != 255
yy = torch.from_numpy(r["target"][known].astype("float32")).to(device)
ww = torch.from_numpy(weights[r["name"]][known]).to(device)
mask = torch.from_numpy(known).to(device)
batch.append((f, r["target"].shape, mask, yy, ww))
optimizer = torch.optim.AdamW(net.parameters(), lr=0.001, weight_decay=0.01)
first = None
last = []
for step in range(steps):
optimizer.zero_grad(set_to_none=True)
loss_value = 0.0
for f, size, mask, yy, ww in batch:
out = torch.nn.functional.interpolate(
net(f), size=size, mode="bilinear", align_corners=False
)[0, 0][mask]
loss = (
torch.nn.functional.binary_cross_entropy_with_logits(out, yy, reduction="none") * ww
).sum()
if not torch.isfinite(loss):
raise ValueError("Nonfinite training loss")
loss.backward()
loss_value += float(loss.detach())
if any(p.grad is not None and not torch.isfinite(p.grad).all() for p in net.parameters()):
raise ValueError("Nonfinite gradient")
optimizer.step()
if first is None:
first = loss_value
last = (last + [loss_value])[-20:]
if step % 25 == 0:
write(
root / "fit-progress.json",
dict(
tag=tag,
step=step + 1,
total=steps,
loss=loss_value,
seconds=time.monotonic() - start,
),
)
if time.monotonic() - start > 240:
raise TimeoutError("Per-fit budget exceeded")
state = root / "models" / (tag + ".pt")
torch.save({k: v.detach().cpu() for k, v in net.state_dict().items()}, state)
metadata = dict(
kind="residual",
kernel=kernel,
seed=seed,
steps=steps,
first_loss=first,
last_loss=last[-1],
last20=last,
parameters=sum(p.numel() for p in net.parameters()),
base=base,
seconds=time.monotonic() - start,
completed=True,
optimizer_convergence_claim=False,
state=state.relative_to(root).as_posix(),
training_groups=sorted({r["group"] for r in records}),
)
net.eval()
return net, metadata
def load(root):
from dataset_store import checksum, read
p = read(root / "protocol.json")
f = read(root / "review-frozen.json")
manifest = read(root / "feature-manifest.json")
assert checksum(Path(__file__)) == f["source_sha256"]
assert checksum(root / "protocol.json") == f["protocol_sha256"] == manifest["protocol_sha256"]
assert f["supervision"] == manifest["supervision"]
data = []
for r in manifest["records"]:
assert checksum(root / r["cache"]) == r["sha256"]
with np.load(root / r["cache"]) as z:
new = z["target"].copy()
old = z["old_target"].copy()
known = old != 255
assert np.array_equal(new[known], old[known])
if r["split"] != "train":
assert np.array_equal(old, new)
data.append(
dict(r, features=z["features"].astype("float32"), target=new, old_target=old)
)
return p, data
def linear(records, which, params):
us = [samples(r["features"], r[which], r, params) for r in records]
return fit(us, 0.01, 500)
def prepare_torch():
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
import torch
torch.set_num_threads(3)
torch.use_deterministic_algorithms(True)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.allow_tf32 = False
torch.backends.cuda.matmul.allow_tf32 = False
def development(root):
import torch
from dataset_store import checksum, write
prepare_torch()
p, data = load(root)
start = time.monotonic()
rows = []
(root / "models").mkdir(exist_ok=False)
for fi, (group, train, held) in enumerate(folds(data)):
assert all(r["group"] != group and r["split"] == "train" for r in train)
old = linear(train, "old_target", p["fit"])
new = linear(train, "target", p["fit"])
for arm in p["arms"]:
tag = f"fold{fi}-{arm}"
net = None
if arm in ["old-linear", "new-linear"]:
lm = old if arm == "old-linear" else new
metadata = dict(
kind="linear", base=lm, completed=True, training_groups=lm["training_groups"]
)
else:
family, seed = arm.split("-")
net, metadata = fit_residual(
train, new, 1 if family == "pointwise" else 3, int(seed), root, tag, p["steps"]
)
metadata["state_sha256"] = checksum(root / metadata["state"])
path = root / "models" / (tag + ".json")
write(path, metadata)
windows = []
for r in held:
pred = (
linear_prediction(r, metadata["base"])
if net is None
else residual_prediction(r, net, new, "cuda")
)
windows.append(dict(name=r["name"], **counts(pred, r["target"])))
row = dict(
phase="development",
arm=arm,
held_out=group,
completed=True,
metrics=aggregate(windows),
windows=windows,
model=path.relative_to(root).as_posix(),
model_sha256=checksum(path),
fitted_groups=metadata["training_groups"],
)
rows.append(row)
write(
root / "development-progress.json",
dict(completed=len(rows), total=32, last=row, seconds=time.monotonic() - start),
)
del net
torch.cuda.empty_cache()
choice = choose(rows)
write(
root / "development-result.json",
dict(
rows=rows,
selection=choice,
seconds=time.monotonic() - start,
protocol_sha256=checksum(root / "protocol.json"),
),
)
write(
root / "selection-frozen.json",
dict(
**choice,
development_sha256=checksum(root / "development-result.json"),
protocol_sha256=checksum(root / "protocol.json"),
),
)
print(json.dumps(choice))
def final_fit(root):
from dataset_store import checksum, read, write
prepare_torch()
p, data = load(root)
choice = read(root / "selection-frozen.json")
train = [r for r in data if r["split"] == "train"]
assert choice["development_sha256"] == checksum(root / "development-result.json")
old = linear(train, "old_target", p["fit"])
new = linear(train, "target", p["fit"])
previous = read(Path("/store/experiments/semantic-nonlinear-20261023/models-frozen.json"))[
"models"
]["linear"]
for k in ["mean", "scale", "coefficients"]:
assert old[k] == previous[k], k
models = {}
for arm in sorted(set(["old-linear"] + choice["selected_arms"])):
if arm in ["old-linear", "new-linear"]:
metadata = dict(kind="linear", base=old if arm == "old-linear" else new, completed=True)
else:
family, seed = arm.split("-")
net, metadata = fit_residual(
train,
new,
1 if family == "pointwise" else 3,
int(seed),
root,
"final-" + arm,
p["steps"],
)
del net
metadata["state_sha256"] = checksum(root / metadata["state"])
models[arm] = metadata
write(
root / "models-frozen.json",
dict(
models=models,
selection_sha256=checksum(root / "selection-frozen.json"),
baseline_exact=True,
protocol_sha256=checksum(root / "protocol.json"),
source_sha256=checksum(Path(__file__)),
production_eligible=False,
),
)
print(json.dumps({"fitted": list(models), "baseline_exact": True}))
def evaluate(root):
import torch
from admission_store import pixel_target
from dataset_store import checksum, read, write
prepare_torch()
p, data = load(root)
models = read(root / "models-frozen.json")
choice = read(root / "selection-frozen.json")
assert models["selection_sha256"] == checksum(root / "selection-frozen.json")
assert not (root / "result.json").exists()
nets = {}
for arm, m in models["models"].items():
if m["kind"] == "residual":
net = network(m["base"], m["kernel"], m["seed"]).cuda()
assert checksum(root / m["state"]) == m["state_sha256"]
net.load_state_dict(
torch.load(root / m["state"], map_location="cuda", weights_only=True)
)
net.eval()
nets[arm] = net
rows = []
audit = {}
for r in data:
if r["split"] != "regression":
continue
preds = {}
for arm, m in models["models"].items():
pred = (
linear_prediction(r, m["base"])
if m["kind"] == "linear"
else residual_prediction(r, nets[arm], m["base"], "cuda")
)
preds[arm] = pred
rows.append(
dict(name=r["name"], group=r["group"], arm=arm, **counts(pred, r["target"]))
)
if r["name"] == "P1":
t = np.frombuffer(
pixel_target(dict(read(root / "p1-audit-runs-final.json"), size=[512, 512])),
dtype="uint8",
).reshape(512, 512)
audit[arm] = aggregate([counts(pred, t)])
np.savez_compressed(root / "cache" / (r["name"] + "-predictions.npz"), **preds)
metrics = {
g: {
a: aggregate([r for r in rows if r["group"] == g and r["arm"] == a])
for a in models["models"]
}
for g in sorted({r["group"] for r in rows})
}
failures = []
for a in choice["selected_arms"]:
if a == "old-linear":
failures.append("No development improvement selected")
continue
for g, mm in metrics.items():
for metric, sign in [("recall", 1), ("fpr", -1)]:
if (
mm[a][metric] is not None
and sign * (mm[a][metric] - mm["old-linear"][metric]) < -1e-12
):
failures.append(a + ": " + g + " " + metric)
if (
audit[a]["recall"] < audit["old-linear"]["recall"]
or audit[a]["fpr"] >= audit["old-linear"]["fpr"]
):
failures.append(a + ": P1 gap gate")
old = read(Path("/store/experiments/semantic-nonlinear-20261023/result.json"))
for r in rows:
if r["arm"] == "old-linear":
before = next(x for x in old["rows"] if x["name"] == r["name"])["variants"]["linear"]
assert all(r[k] == before[k] for k in ["tp", "fn", "fp", "tn", "ignored"])
assert audit["old-linear"] == old["diagnostic"]["linear"]
result = dict(
rows=rows,
metrics=metrics,
diagnostic=audit,
selection=choice,
accepted=not failures,
failures=failures,
production_eligible=False,
baseline_exact=True,
models_sha256=checksum(root / "models-frozen.json"),
source_sha256=checksum(Path(__file__)),
protocol_sha256=checksum(root / "protocol.json"),
)
write(root / "result.json", result)
print(
json.dumps(
{
"metrics": metrics,
"diagnostic": audit,
"accepted": not failures,
"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"))
a = ap.parse_args()
{"development": development, "fit": final_fit, "evaluate": evaluate}[a.phase](a.root)