Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
532 lines
20 KiB
Python
532 lines
20 KiB
Python
"""Offline adaptation of installed Mask2Former high-resolution FPN tail.
|
|
|
|
Whole physical-street folds, fixed recipe, paired optimizer control; no deployment.
|
|
The backbone, lateral fusion and deformable-attention encoder remain frozen.
|
|
"""
|
|
|
|
import argparse
|
|
import json
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
from pixel_growth_probe import aggregate, counts
|
|
from spatial_decoder_probe import dense_weights, linear, linear_prediction, prepare_torch
|
|
from street_holdout_probe import folds
|
|
|
|
|
|
def choose(rows, seeds):
|
|
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 physical streets required")
|
|
expected = {"old-linear", "new-linear"} | {
|
|
f"{f}-{s}" for f in ["head", "decoder"] for s in seeds
|
|
}
|
|
if {r["arm"] for r in rows} != expected:
|
|
raise ValueError("Incomplete arms")
|
|
summary = {}
|
|
for arm in sorted(expected):
|
|
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 folds")
|
|
if any(r["held_out"] in r["fitted_groups"] for r in rr):
|
|
raise ValueError("Physical-street leakage")
|
|
errors = [(1 - r["metrics"]["recall"] + r["metrics"]["fpr"]) / 2 for r in rr]
|
|
summary[arm] = dict(
|
|
mean=float(np.mean(errors)),
|
|
worst=max(errors),
|
|
completed=all(r["completed"] for r in rr),
|
|
)
|
|
|
|
def better(a, b):
|
|
return (
|
|
summary[a]["completed"]
|
|
and summary[a]["mean"] < summary[b]["mean"] - 1e-12
|
|
and summary[a]["worst"] <= summary[b]["worst"] + 1e-12
|
|
)
|
|
|
|
eligible = []
|
|
for family in ["head", "decoder"]:
|
|
if all(
|
|
better(f"{family}-{s}", "new-linear")
|
|
and (family != "decoder" or better(f"decoder-{s}", f"head-{s}"))
|
|
for s in seeds
|
|
):
|
|
eligible.append(family)
|
|
selected = (
|
|
min(
|
|
eligible,
|
|
key=lambda f: (
|
|
max(summary[f"{f}-{s}"]["mean"] for s in seeds),
|
|
max(summary[f"{f}-{s}"]["worst"] for s in seeds),
|
|
f,
|
|
),
|
|
)
|
|
if eligible
|
|
else "new-linear"
|
|
)
|
|
return dict(
|
|
selected_family=selected,
|
|
selected_arms=[f"{selected}-{s}" for s in seeds] if eligible else ["new-linear"],
|
|
eligible_families=eligible,
|
|
summaries=summary,
|
|
all_seeds_required=True,
|
|
frozen_before_controls=True,
|
|
)
|
|
|
|
|
|
def network(base, state, family):
|
|
import torch
|
|
from torch import nn
|
|
|
|
if family not in ["head", "decoder"]:
|
|
raise ValueError("Unsupported adaptation family")
|
|
|
|
class Tail(nn.Module):
|
|
def __init__(self):
|
|
super().__init__()
|
|
self.layer = nn.Sequential(
|
|
nn.Conv2d(256, 256, 3, padding=1, bias=False), nn.GroupNorm(32, 256), nn.ReLU()
|
|
)
|
|
self.projection = nn.Conv2d(256, 256, 1)
|
|
self.load_state_dict(state)
|
|
for p in self.parameters():
|
|
p.requires_grad_(family == "decoder")
|
|
self.head = nn.Conv2d(256, 1, 1)
|
|
with torch.no_grad():
|
|
self.head.weight.copy_(torch.tensor(base["coefficients"][1:])[:, None, None][None])
|
|
self.head.bias.fill_(base["coefficients"][0])
|
|
self.register_buffer(
|
|
"mean", torch.tensor(base["mean"], dtype=torch.float32)[None, :, None, None]
|
|
)
|
|
self.register_buffer(
|
|
"scale", torch.tensor(base["scale"], dtype=torch.float32)[None, :, None, None]
|
|
)
|
|
|
|
def features(self, x):
|
|
with torch.autocast("cuda", dtype=torch.bfloat16):
|
|
return self.projection(self.layer(x)).float()
|
|
|
|
def classify(self, f):
|
|
return self.head((f - self.mean) / self.scale)
|
|
|
|
return Tail()
|
|
|
|
|
|
def prediction(record, net):
|
|
import torch
|
|
|
|
with torch.inference_mode():
|
|
fs = []
|
|
for k in range(4):
|
|
f = net.features(
|
|
torch.from_numpy(record["tail_input"][k : k + 1]).cuda().view(torch.bfloat16)
|
|
)
|
|
fs.append(torch.rot90(f, -k, [-2, -1]))
|
|
f = torch.stack(fs).mean(0).half().float()
|
|
logits = net.classify(f)
|
|
logits = torch.nn.functional.interpolate(
|
|
logits, size=record["target"].shape, mode="bilinear", align_corners=False
|
|
)
|
|
return (logits[0, 0] >= 0).cpu().numpy()
|
|
|
|
|
|
def fit_tail(
|
|
records,
|
|
base,
|
|
family,
|
|
seed,
|
|
root,
|
|
tag,
|
|
protocol,
|
|
*,
|
|
weight_policy="uniform",
|
|
control_policy=None,
|
|
background_policy=None,
|
|
):
|
|
import torch
|
|
from dataset_store import checksum, write
|
|
|
|
start = time.monotonic()
|
|
torch.manual_seed(seed)
|
|
rng = np.random.default_rng(seed)
|
|
state = torch.load(root / "pretrained-tail.pt", map_location="cpu", weights_only=True)
|
|
net = network(base, state, family).cuda().eval()
|
|
if control_policy is not None:
|
|
from coverage_mass_control import prepare, rotation, schedule_digest
|
|
|
|
records, weights = prepare(records, control_policy)
|
|
if set(base["training_groups"]) != {r["group"] for r in records}:
|
|
raise ValueError("Control records differ from initialization groups")
|
|
elif weight_policy == "uniform":
|
|
weights = dense_weights(records)
|
|
elif weight_policy == "release_balanced":
|
|
from supervision_balance import release_balanced_weights
|
|
|
|
weights = release_balanced_weights(records)
|
|
else:
|
|
raise ValueError("Unsupported loss-weight policy")
|
|
if background_policy is not None:
|
|
if background_policy != "frozen_window_mass" or control_policy is None:
|
|
raise ValueError("Background admission requires the paired control recipe")
|
|
from background_admission import prepare_background
|
|
|
|
records, weights = prepare_background(records, weights)
|
|
batch = []
|
|
for r in records:
|
|
known = r["target"] != 255
|
|
batch.append(
|
|
(
|
|
torch.from_numpy(r["tail_input"]).cuda().view(torch.bfloat16),
|
|
r["target"].shape,
|
|
torch.from_numpy(known).cuda(),
|
|
torch.from_numpy(r["target"][known].astype("float32")).cuda(),
|
|
torch.from_numpy(weights[r["name"]][known]).cuda(),
|
|
)
|
|
)
|
|
params = [dict(params=net.head.parameters(), lr=protocol["lr_head"])]
|
|
if family == "decoder":
|
|
params.append(
|
|
dict(
|
|
params=list(net.layer.parameters()) + list(net.projection.parameters()),
|
|
lr=protocol["lr_tail"],
|
|
)
|
|
)
|
|
optimizer = torch.optim.AdamW(params, weight_decay=protocol["weight_decay"])
|
|
first = None
|
|
last = []
|
|
for step in range(protocol["steps"]):
|
|
optimizer.zero_grad(set_to_none=True)
|
|
value = 0.0
|
|
order = range(len(batch)) if control_policy is not None else rng.permutation(len(batch))
|
|
for index in order:
|
|
xx, size, mask, yy, ww = batch[index]
|
|
if control_policy is not None and not bool(mask.any()):
|
|
continue
|
|
k = (
|
|
rotation(seed, step, records[index]["sample_id"])
|
|
if control_policy is not None
|
|
else int(rng.integers(4))
|
|
)
|
|
f = torch.rot90(net.features(xx[k : k + 1]), -k, [-2, -1]).half().float()
|
|
out = torch.nn.functional.interpolate(
|
|
net.classify(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 loss")
|
|
loss.backward()
|
|
value += float(loss.detach())
|
|
grad = torch.nn.utils.clip_grad_norm_(
|
|
net.parameters(), protocol["clip_grad_norm"], error_if_nonfinite=True
|
|
)
|
|
optimizer.step()
|
|
if first is None:
|
|
first = value
|
|
last = (last + [value])[-20:]
|
|
if step % 10 == 0 or step + 1 == protocol["steps"]:
|
|
write(
|
|
root / "fit-progress.json",
|
|
dict(
|
|
tag=tag,
|
|
step=step + 1,
|
|
total=protocol["steps"],
|
|
loss=value,
|
|
gradient_norm=float(grad),
|
|
seconds=time.monotonic() - start,
|
|
),
|
|
)
|
|
if time.monotonic() - start > protocol["resources"]["max_neural_fit_seconds"]:
|
|
raise TimeoutError("Fixed fit budget exceeded")
|
|
delta = {
|
|
k: float(torch.linalg.vector_norm(net.state_dict()[k].cpu() - v)) for k, v in state.items()
|
|
}
|
|
assert (
|
|
any(v > 0 for v in delta.values())
|
|
if family == "decoder"
|
|
else all(v == 0 for v in delta.values())
|
|
)
|
|
path = root / "models" / (tag + ".pt")
|
|
torch.save({k: v.detach().cpu() for k, v in net.state_dict().items()}, path)
|
|
meta = dict(
|
|
kind="tail",
|
|
family=family,
|
|
seed=seed,
|
|
base=base,
|
|
state=path.relative_to(root).as_posix(),
|
|
state_sha256=checksum(path),
|
|
steps=protocol["steps"],
|
|
completed=True,
|
|
first_loss=first,
|
|
last_loss=last[-1],
|
|
last20=last,
|
|
pretrained_parameter_delta_l2=delta,
|
|
loss_weight_policy=weight_policy,
|
|
trained_parameters=sum(p.numel() for p in net.parameters() if p.requires_grad),
|
|
training_groups=base["training_groups"],
|
|
seconds=time.monotonic() - start,
|
|
convergence_claim=False,
|
|
)
|
|
if control_policy is not None:
|
|
meta.update(
|
|
control_policy=control_policy,
|
|
schedule_sha256=schedule_digest(records, seed, protocol["steps"]),
|
|
accumulation_order=[r["sample_id"] for r in records],
|
|
)
|
|
if background_policy is not None:
|
|
meta["background_policy"] = background_policy
|
|
return net, meta
|
|
|
|
|
|
def load(root):
|
|
from dataset_store import checksum, read
|
|
|
|
protocol = read(root / "protocol.json")
|
|
frozen = read(root / "run-frozen.json")
|
|
manifest = read(root / "decoder-cache.json")
|
|
assert checksum(Path(__file__)) == frozen["source_sha256"]
|
|
assert (
|
|
checksum(root / "protocol.json") == frozen["protocol_sha256"] == manifest["protocol_sha256"]
|
|
)
|
|
assert checksum(root / "pretrained-tail.pt") == manifest["pretrained_tail_sha256"]
|
|
assert checksum(root / "decoder-cache.json") == frozen["cache_manifest_sha256"]
|
|
data = []
|
|
for r in manifest["records"]:
|
|
assert checksum(root / r["cache"]) == r["sha256"]
|
|
with np.load(root / r["cache"]) as z:
|
|
data.append(
|
|
dict(
|
|
r,
|
|
**{
|
|
k: z[k].astype("float32") if k == "features" else z[k].copy()
|
|
for k in ["tail_input", "features", "target", "old_target"]
|
|
},
|
|
)
|
|
)
|
|
return protocol, data
|
|
|
|
|
|
def development(root):
|
|
import torch
|
|
from dataset_store import checksum, read, write
|
|
|
|
prepare_torch()
|
|
p, data = load(root)
|
|
start = time.monotonic()
|
|
rows = []
|
|
(root / "models").mkdir(exist_ok=False)
|
|
parent = read(Path("/store/experiments") / "semantic-spatial-20261023/development-result.json")
|
|
predictions = {r["name"]: {} for r in data if r["split"] == "train"}
|
|
for fi, (group, train, held) in enumerate(folds(data)):
|
|
old = linear(train, "old_target", p["fit"])
|
|
new = linear(train, "target", p["fit"])
|
|
arms = ["old-linear", "new-linear"] + [
|
|
f"{f}-{s}" for s in p["seeds"] for f in ["head", "decoder"]
|
|
]
|
|
for arm in arms:
|
|
tag = f"fold{fi}-{arm}"
|
|
net = None
|
|
if arm in ["old-linear", "new-linear"]:
|
|
meta = dict(
|
|
kind="linear",
|
|
base=old if arm == "old-linear" else new,
|
|
completed=True,
|
|
training_groups=new["training_groups"],
|
|
)
|
|
else:
|
|
family, seed = arm.split("-")
|
|
net, meta = fit_tail(train, new, family, int(seed), root, tag, p)
|
|
path = root / "models" / (tag + ".json")
|
|
write(path, meta)
|
|
windows = []
|
|
for r in held:
|
|
pred = linear_prediction(r, meta["base"]) if net is None else prediction(r, net)
|
|
windows.append(dict(name=r["name"], **counts(pred, r["target"])))
|
|
predictions[r["name"]][arm] = pred
|
|
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=meta["training_groups"],
|
|
)
|
|
if net is None:
|
|
before = next(
|
|
x for x in parent["rows"] if x["arm"] == arm and x["held_out"] == group
|
|
)
|
|
assert row["metrics"] == before["metrics"] and row["windows"] == before["windows"]
|
|
rows.append(row)
|
|
write(
|
|
root / "development-progress.json",
|
|
dict(completed=len(rows), total=32, last=row, seconds=time.monotonic() - start),
|
|
)
|
|
print(tag + " done", flush=True)
|
|
del net
|
|
torch.cuda.empty_cache()
|
|
if time.monotonic() - start > p["resources"]["max_development_seconds"]:
|
|
raise TimeoutError("Development budget exceeded")
|
|
for name, preds in predictions.items():
|
|
np.savez_compressed(root / "cache" / (name + "-dev-predictions.npz"), **preds)
|
|
selection = choose(rows, p["seeds"])
|
|
write(
|
|
root / "development-result.json",
|
|
dict(
|
|
rows=rows,
|
|
selection=selection,
|
|
seconds=time.monotonic() - start,
|
|
protocol_sha256=checksum(root / "protocol.json"),
|
|
),
|
|
)
|
|
write(
|
|
root / "selection-frozen.json",
|
|
dict(
|
|
**selection,
|
|
development_sha256=checksum(root / "development-result.json"),
|
|
protocol_sha256=checksum(root / "protocol.json"),
|
|
),
|
|
)
|
|
print(json.dumps(selection))
|
|
|
|
|
|
def final_fit(root):
|
|
from dataset_store import checksum, read, write
|
|
|
|
prepare_torch()
|
|
p, data = load(root)
|
|
choice = read(root / "selection-frozen.json")
|
|
assert choice["development_sha256"] == checksum(root / "development-result.json")
|
|
train = [r for r in data if r["split"] == "train"]
|
|
old = linear(train, "old_target", p["fit"])
|
|
new = linear(train, "target", p["fit"])
|
|
previous = read(Path("/store/experiments") / "semantic-spatial-20261023/models-frozen.json")
|
|
models = {}
|
|
for a, b in [("old-linear", old), ("new-linear", new)]:
|
|
for k in ["coefficients", "mean", "scale"]:
|
|
assert previous["models"][a]["base"][k] == b[k]
|
|
for arm in sorted(set(["old-linear", "new-linear"] + choice["selected_arms"])):
|
|
if arm in ["old-linear", "new-linear"]:
|
|
meta = dict(kind="linear", base=old if arm == "old-linear" else new, completed=True)
|
|
else:
|
|
family, seed = arm.split("-")
|
|
net, meta = fit_tail(train, new, family, int(seed), root, "final-" + arm, p)
|
|
del net
|
|
models[arm] = meta
|
|
write(
|
|
root / "models-frozen.json",
|
|
dict(
|
|
models=models,
|
|
selection_sha256=checksum(root / "selection-frozen.json"),
|
|
source_sha256=checksum(Path(__file__)),
|
|
protocol_sha256=checksum(root / "protocol.json"),
|
|
production_eligible=False,
|
|
),
|
|
)
|
|
print(json.dumps(dict(final_models=list(models))))
|
|
|
|
|
|
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")
|
|
and not (root / "result.json").exists()
|
|
)
|
|
rows = []
|
|
audit = {}
|
|
nets = {}
|
|
pretrained = torch.load(root / "pretrained-tail.pt", map_location="cpu", weights_only=True)
|
|
for arm, m in models["models"].items():
|
|
if m["kind"] == "tail":
|
|
net = network(m["base"], pretrained, m["family"]).cuda().eval()
|
|
assert checksum(root / m["state"]) == m["state_sha256"]
|
|
net.load_state_dict(
|
|
torch.load(root / m["state"], map_location="cuda", weights_only=True)
|
|
)
|
|
nets[arm] = net
|
|
for r in data:
|
|
if r["split"] != "regression":
|
|
continue
|
|
preds = {}
|
|
for a, m in models["models"].items():
|
|
pred = (
|
|
linear_prediction(r, m["base"]) if m["kind"] == "linear" else prediction(r, nets[a])
|
|
)
|
|
preds[a] = pred
|
|
rows.append(dict(name=r["name"], group=r["group"], arm=a, **counts(pred, r["target"])))
|
|
if r["name"] == "P1":
|
|
target = np.frombuffer(
|
|
pixel_target(dict(read(root / "p1-audit-runs-final.json"), size=[512, 512])),
|
|
dtype="uint8",
|
|
).reshape(512, 512)
|
|
audit[a] = aggregate([counts(pred, target)])
|
|
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})
|
|
}
|
|
previous = read(Path("/store/experiments") / "semantic-spatial-20261023/result.json")
|
|
for a in ["old-linear", "new-linear"]:
|
|
assert audit[a] == previous["diagnostic"][a]
|
|
for g in metrics:
|
|
assert metrics[g][a] == previous["metrics"][g][a]
|
|
failures = []
|
|
if choice["selected_family"] == "new-linear":
|
|
failures.append("No development improvement selected")
|
|
for a in choice["selected_arms"]:
|
|
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 + ": P1gap")
|
|
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(
|
|
dict(accepted=result["accepted"], failures=failures, metrics=metrics, diagnostic=audit)
|
|
)
|
|
)
|
|
|
|
|
|
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": evaluate}[args.phase](args.root)
|