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,374 @@
|
||||
"""Frozen visual representation probe. Offline only; no map publication."""
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
from grouped_selection_study import objective, select, transfer_gate
|
||||
from object_assembly_study import measured
|
||||
from object_proposal_study import aggregate, labels, masks, save_new, sha, timestamp
|
||||
from paint_hypothesis_study import fit_classifier, probability
|
||||
from PIL import Image
|
||||
from shapely.geometry import shape
|
||||
from shapely.ops import unary_union
|
||||
|
||||
VARIANTS = ["handcrafted14", "visual512", "fused526", "native_paint"]
|
||||
|
||||
|
||||
def fractional_weights(mask, shape_hw):
|
||||
"""Retain thin-object support when pooling stride-four image features."""
|
||||
h, w = shape_hw
|
||||
weights = cv2.resize(mask.astype(np.float32), (w, h), interpolation=cv2.INTER_AREA)
|
||||
total = float(weights.sum())
|
||||
if total <= 0:
|
||||
raise ValueError("Empty pooling support")
|
||||
return weights / total
|
||||
|
||||
|
||||
def assessed(candidates, reviewed):
|
||||
result = measured(candidates, reviewed)
|
||||
result["unsupported_sparse"] = result["unsupported"]
|
||||
bg = unary_union([shape(g) for g in reviewed.get("complete_background", [])])
|
||||
ls = labels(candidates, reviewed)
|
||||
bad = []
|
||||
for c, label in zip(candidates, ls, strict=True):
|
||||
p = shape(c["geometry"])
|
||||
if label == 0 or (
|
||||
label != 1 and not bg.is_empty and p.intersection(bg).area / max(p.area, 1e-9) >= 0.9
|
||||
):
|
||||
bad.append(c["id"])
|
||||
result["unsupported"] = len(bad)
|
||||
result["false_ids"] = bad
|
||||
return result
|
||||
|
||||
|
||||
def check_inputs(root):
|
||||
for name, digest in json.loads((root / "input-hashes.json").read_text()).items():
|
||||
if sha(root / name) != digest:
|
||||
raise ValueError("Changed frozen input: " + name)
|
||||
|
||||
|
||||
def extract(root):
|
||||
import torch
|
||||
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
|
||||
|
||||
torch.set_num_threads(3)
|
||||
cv2.setNumThreads(3)
|
||||
check_inputs(root)
|
||||
inventory = json.loads((root / "model-inventory.json").read_text())
|
||||
for name, digest in inventory["files"].items():
|
||||
assert sha(Path("/model") / name) == digest
|
||||
processor = AutoImageProcessor.from_pretrained("/model", local_files_only=True)
|
||||
model = (
|
||||
Mask2FormerForUniversalSegmentation.from_pretrained("/model", local_files_only=True)
|
||||
.cuda()
|
||||
.eval()
|
||||
)
|
||||
for p in model.parameters():
|
||||
p.requires_grad_(False)
|
||||
records = json.loads((root / "candidates.json").read_text())["records"]
|
||||
folder = root / "features"
|
||||
folder.mkdir(exist_ok=True)
|
||||
receipts = []
|
||||
for i, record in enumerate(records):
|
||||
rgb_path = root / "data" / (record["id"] + ".png")
|
||||
tensors = processor(
|
||||
images=Image.open(rgb_path).convert("RGB"),
|
||||
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):
|
||||
output = model(**tensors, output_hidden_states=True)
|
||||
feature = output.pixel_decoder_last_hidden_state[0].float()
|
||||
assert feature.shape[0] == 256, feature.shape
|
||||
classes = output.class_queries_logits[0].float().softmax(-1)[:, :-1]
|
||||
queries = output.masks_queries_logits[0].float().sigmoid()
|
||||
semantic = torch.einsum("qc,qhw->chw", classes, queries)
|
||||
native = semantic[[23, 24]].sum(0) / semantic.sum(0).clamp_min(1e-8)
|
||||
cs = record["variants"]["retained"]
|
||||
inside, rings, native_weights = [], [], []
|
||||
for c in cs:
|
||||
mask = masks(shape(c["geometry"]))
|
||||
ring = (
|
||||
cv2.dilate(
|
||||
mask.astype(np.uint8), cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (23, 23))
|
||||
)
|
||||
> 0
|
||||
) & ~mask
|
||||
inside.append(fractional_weights(mask, feature.shape[-2:]).ravel())
|
||||
rings.append(fractional_weights(ring, feature.shape[-2:]).ravel())
|
||||
native_weights.append(fractional_weights(mask, native.shape).ravel())
|
||||
if cs:
|
||||
w = torch.as_tensor(np.asarray(inside + rings), device="cuda")
|
||||
pooled = (w @ feature.flatten(1).T).cpu().numpy()
|
||||
visual = np.concatenate([pooled[: len(cs)], pooled[len(cs) :]], axis=1)
|
||||
native_score = (
|
||||
(torch.as_tensor(np.asarray(native_weights), device="cuda") @ native.flatten())
|
||||
.cpu()
|
||||
.numpy()
|
||||
)
|
||||
else:
|
||||
visual, native_score = np.empty((0, 512)), np.empty(0)
|
||||
path = folder / (record["id"] + ".npz")
|
||||
assert not path.exists()
|
||||
np.savez_compressed(
|
||||
path, visual=visual, native=native_score, ids=np.asarray([c["id"] for c in cs])
|
||||
)
|
||||
receipts.append(
|
||||
dict(
|
||||
id=record["id"],
|
||||
path=str(path.relative_to(root)),
|
||||
sha256=sha(path),
|
||||
rgb_sha256=sha(rgb_path),
|
||||
feature_shape=list(feature.shape),
|
||||
candidates=len(cs),
|
||||
)
|
||||
)
|
||||
del output, tensors, feature, semantic, native
|
||||
print(json.dumps(dict(completed=i + 1, total=len(records))), flush=True)
|
||||
save_new(
|
||||
root / "features.json",
|
||||
dict(
|
||||
**timestamp(),
|
||||
source_sha256=sha(Path(__file__)),
|
||||
candidate_sha256=sha(root / "candidates.json"),
|
||||
model_inventory_sha256=sha(root / "model-inventory.json"),
|
||||
records=receipts,
|
||||
max_gpu_bytes=int(torch.cuda.max_memory_allocated()),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def loaded(root):
|
||||
records = json.loads((root / "candidates.json").read_text())["records"]
|
||||
review = json.loads((root / "review-frozen.json").read_text())["records"]
|
||||
feature_receipt = json.loads((root / "features.json").read_text())
|
||||
if feature_receipt["source_sha256"] != sha(Path(__file__)):
|
||||
raise ValueError("Feature implementation changed")
|
||||
data = {}
|
||||
for r in records:
|
||||
path = root / "features" / (r["id"] + ".npz")
|
||||
receipt = next(a for a in feature_receipt["records"] if a["id"] == r["id"])
|
||||
assert sha(path) == receipt["sha256"]
|
||||
z = np.load(path)
|
||||
cs = r["variants"]["retained"]
|
||||
assert z["ids"].tolist() == [c["id"] for c in cs]
|
||||
hand = np.asarray([c["features"][:14] for c in cs]).reshape(-1, 14)
|
||||
data[r["id"]] = dict(
|
||||
handcrafted14=hand,
|
||||
visual512=z["visual"],
|
||||
fused526=np.concatenate([hand, z["visual"]], axis=1),
|
||||
native_paint=z["native"],
|
||||
)
|
||||
return records, review, data
|
||||
|
||||
|
||||
def fit_head(records, review, data, variant, l2):
|
||||
x, y = [], []
|
||||
for r in records:
|
||||
labs = labels(r["variants"]["retained"], review[r["id"]])
|
||||
eligible = labs >= 0
|
||||
x.append(data[r["id"]][variant][eligible])
|
||||
y.append(labs[eligible])
|
||||
xx, yy = np.concatenate(x), np.concatenate(y)
|
||||
if min(np.sum(yy == 0), np.sum(yy == 1)) < 2:
|
||||
raise ValueError("Insufficient reviewed classes")
|
||||
model = fit_classifier(xx, yy, l2, 500)
|
||||
model["positive"] = int(np.sum(yy == 1))
|
||||
model["negative"] = int(np.sum(yy == 0))
|
||||
return model
|
||||
|
||||
|
||||
def predict(records, data, variant, model=None):
|
||||
return {
|
||||
r["id"]: (
|
||||
data[r["id"]][variant].tolist()
|
||||
if variant == "native_paint"
|
||||
else probability(data[r["id"]][variant], model).tolist()
|
||||
if len(r["variants"]["retained"])
|
||||
else []
|
||||
)
|
||||
for r in records
|
||||
}
|
||||
|
||||
|
||||
def evaluation(records, review, probabilities, threshold):
|
||||
rows = []
|
||||
for r in records:
|
||||
accepted = [
|
||||
c
|
||||
for c, p in zip(r["variants"]["retained"], probabilities[r["id"]], strict=True)
|
||||
if p >= threshold
|
||||
]
|
||||
rows.append(
|
||||
dict(
|
||||
id=r["id"],
|
||||
street=r["street"],
|
||||
accepted_ids=[c["id"] for c in accepted],
|
||||
**assessed(accepted, review[r["id"]]),
|
||||
)
|
||||
)
|
||||
return dict(
|
||||
rows=rows,
|
||||
summary=aggregate(rows),
|
||||
streets={
|
||||
s: aggregate([r for r in rows if r["street"] == s])
|
||||
for s in sorted({r["street"] for r in records})
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def rank(choice):
|
||||
return choice["worst_street"], choice["macro_family"], choice["found"]
|
||||
|
||||
|
||||
def train(root):
|
||||
check_inputs(root)
|
||||
records, review, data = loaded(root)
|
||||
dev = [r for r in records if r["split"] == "development"]
|
||||
assert not ({r["street"] for r in dev} & {"pokrovka", "sadovaya-karetnaya"})
|
||||
protocol = json.loads((root / "protocol.json").read_text())
|
||||
ceiling = {r["id"]: measured(r["variants"]["retained"], review[r["id"]]) for r in dev}
|
||||
variants = {}
|
||||
for variant in VARIANTS:
|
||||
experiments = []
|
||||
for l2 in [0.0] if variant == "native_paint" else protocol["regularization"]:
|
||||
scores, folds = {}, {}
|
||||
if variant == "native_paint":
|
||||
scores = predict(dev, data, variant)
|
||||
else:
|
||||
for street in sorted({r["street"] for r in dev}):
|
||||
training = [r for r in dev if r["street"] != street]
|
||||
validation = [r for r in dev if r["street"] == street]
|
||||
model = fit_head(training, review, data, variant, l2)
|
||||
scores.update(predict(validation, data, variant, model))
|
||||
folds[street] = dict(
|
||||
training_streets=sorted({r["street"] for r in training}), model=model
|
||||
)
|
||||
sweep = []
|
||||
for threshold in protocol["thresholds"]:
|
||||
result = evaluation(dev, review, scores, threshold)
|
||||
sweep.append(
|
||||
dict(
|
||||
threshold=threshold,
|
||||
**result["summary"],
|
||||
**objective(result["rows"], ceiling),
|
||||
)
|
||||
)
|
||||
selected = select(sweep)
|
||||
experiments.append(dict(l2=l2, selected=selected, folds=folds, sweep=sweep))
|
||||
feasible = [e for e in experiments if e["selected"] is not None]
|
||||
best = max(feasible, key=lambda e: (*rank(e["selected"]), e["l2"])) if feasible else None
|
||||
model = (
|
||||
fit_head(dev, review, data, variant, best["l2"])
|
||||
if best and variant != "native_paint"
|
||||
else None
|
||||
)
|
||||
variants[variant] = dict(
|
||||
selected=best["selected"] if best else None,
|
||||
l2=best["l2"] if best else None,
|
||||
model=model,
|
||||
experiments=experiments,
|
||||
)
|
||||
print(
|
||||
json.dumps(
|
||||
dict(
|
||||
variant=variant,
|
||||
selected=variants[variant]["selected"],
|
||||
l2=variants[variant]["l2"],
|
||||
)
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
choices = [v for v in VARIANTS if variants[v]["selected"] is not None]
|
||||
chosen = (
|
||||
max(choices, key=lambda v: (*rank(variants[v]["selected"]), -VARIANTS.index(v)))
|
||||
if choices
|
||||
else None
|
||||
)
|
||||
save_new(
|
||||
root / "models-frozen.json",
|
||||
dict(
|
||||
**timestamp(),
|
||||
chosen=chosen,
|
||||
variants=variants,
|
||||
source_sha256=sha(Path(__file__)),
|
||||
hashes={
|
||||
n: sha(root / n)
|
||||
for n in [
|
||||
"protocol.json",
|
||||
"review-frozen.json",
|
||||
"inputs.json",
|
||||
"input-hashes.json",
|
||||
"candidates.json",
|
||||
"features.json",
|
||||
"model-inventory.json",
|
||||
]
|
||||
},
|
||||
),
|
||||
)
|
||||
print("chosen", chosen)
|
||||
|
||||
|
||||
def evaluate(root):
|
||||
check_inputs(root)
|
||||
records, review, data = loaded(root)
|
||||
frozen = json.loads((root / "models-frozen.json").read_text())
|
||||
assert frozen["source_sha256"] == sha(Path(__file__))
|
||||
for n, h in frozen["hashes"].items():
|
||||
assert sha(root / n) == h, n
|
||||
old = json.loads(Path("/objectstudy/models-frozen.json").read_text())["models"][
|
||||
"shape_appearance"
|
||||
]["model"]
|
||||
results = {}
|
||||
for cohort in ["regression", "heldout"]:
|
||||
rows = [r for r in records if r["split"] == cohort]
|
||||
baseline = evaluation(rows, review, predict(rows, data, "handcrafted14", old), 0.15)
|
||||
variants = {}
|
||||
for v, artifact in frozen["variants"].items():
|
||||
if artifact["selected"] is not None:
|
||||
out = evaluation(
|
||||
rows,
|
||||
review,
|
||||
predict(rows, data, v, artifact["model"]),
|
||||
artifact["selected"]["threshold"],
|
||||
)
|
||||
variants[v] = dict(**out, gate_vs_frozen=transfer_gate(baseline, out))
|
||||
for out in variants.values():
|
||||
if "handcrafted14" in variants:
|
||||
out["gate_vs_same_data_handcrafted"] = transfer_gate(variants["handcrafted14"], out)
|
||||
ceiling = evaluation(
|
||||
rows, review, {r["id"]: [1.0] * len(r["variants"]["retained"]) for r in rows}, 0.0
|
||||
)
|
||||
results[cohort] = dict(baseline=baseline, variants=variants, ceiling=ceiling)
|
||||
save_new(
|
||||
root / "results.json",
|
||||
dict(
|
||||
**timestamp(),
|
||||
chosen=frozen["chosen"],
|
||||
models_sha256=sha(root / "models-frozen.json"),
|
||||
cohorts=results,
|
||||
),
|
||||
)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
k: dict(
|
||||
baseline=v["baseline"]["summary"],
|
||||
variants={
|
||||
n: dict(**x["summary"], gate=x["gate_vs_frozen"])
|
||||
for n, x in v["variants"].items()
|
||||
},
|
||||
ceiling=v["ceiling"]["summary"],
|
||||
)
|
||||
for k, v in results.items()
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
{"extract": extract, "train": train, "evaluate": evaluate}[sys.argv[1]](Path(sys.argv[2]))
|
||||
Reference in New Issue
Block a user