Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
335 lines
13 KiB
Python
335 lines
13 KiB
Python
"""Uniform quarter-turn feature pooling; offline admission only, never publishes maps."""
|
|
|
|
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 masks, save_new, sha, timestamp
|
|
from paint_hypothesis_study import probability
|
|
from PIL import Image
|
|
from shapely.geometry import shape
|
|
from visual_admission_study import (
|
|
check_inputs,
|
|
evaluation,
|
|
fit_head,
|
|
fractional_weights,
|
|
predict,
|
|
rank,
|
|
)
|
|
|
|
VARIANTS = ["single512", "c4_512", "c4_fused"]
|
|
|
|
|
|
def c4_mean(orbit):
|
|
"""Uniform finite-group average; no label, score, or angle-based selection."""
|
|
if orbit.ndim != 3 or orbit.shape[0] != 4 or not np.isfinite(orbit).all():
|
|
raise ValueError("Expected four finite descriptor arrays")
|
|
return orbit.astype(np.float64).mean(axis=0).astype(np.float32)
|
|
|
|
|
|
def supports(candidates):
|
|
inside = [masks(shape(c["geometry"])) for c in candidates]
|
|
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (23, 23))
|
|
rings = [(cv2.dilate(m.astype(np.uint8), kernel) > 0) & ~m for m in inside]
|
|
return inside + rings
|
|
|
|
|
|
def descriptor_orbit(rgb, support, model, processor):
|
|
import torch
|
|
|
|
if not support:
|
|
return np.empty((4, 0, 512), dtype=np.float32)
|
|
n = len(support) // 2
|
|
result = []
|
|
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):
|
|
output = model(**tensors, output_hidden_states=True)
|
|
feat = torch.rot90(output.pixel_decoder_last_hidden_state[0].float(), -k, [-2, -1])
|
|
assert tuple(feat.shape) == (256, 128, 128), feat.shape
|
|
weights = np.asarray([fractional_weights(m, feat.shape[-2:]).ravel() for m in support])
|
|
pooled = (torch.as_tensor(weights, device="cuda") @ feat.flatten(1).T).cpu().numpy()
|
|
result.append(np.concatenate([pooled[:n], pooled[n:]], axis=1))
|
|
del output, tensors, feat
|
|
return np.asarray(result)
|
|
|
|
|
|
def extract(root):
|
|
import torch
|
|
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
|
|
|
|
torch.set_num_threads(3)
|
|
cv2.setNumThreads(3)
|
|
check_inputs(root)
|
|
for name, h in json.loads((root / "model-inventory.json").read_text())["files"].items():
|
|
assert sha(Path("/model") / name) == h, name
|
|
processor = AutoImageProcessor.from_pretrained("/model", local_files_only=True)
|
|
model = (
|
|
Mask2FormerForUniversalSegmentation.from_pretrained("/model", local_files_only=True)
|
|
.eval()
|
|
.cuda()
|
|
)
|
|
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=False)
|
|
receipts = []
|
|
for i, rec in enumerate(records):
|
|
rgb_path = root / "data" / (rec["id"] + ".png")
|
|
rgb = np.asarray(Image.open(rgb_path).convert("RGB"))
|
|
cs = rec["variants"]["retained"]
|
|
support = supports(cs)
|
|
orbit = descriptor_orbit(rgb, support, model, processor)
|
|
mean = c4_mean(orbit)
|
|
checks = []
|
|
# Predeclared regression cases: actual independent rotated-input inference,
|
|
# beyond merely permuting already computed descriptors.
|
|
if rec["id"] in ["pokrovka-2", "pokrovka-visual-2"]:
|
|
for turn in [1, 2, 3]:
|
|
rotated = descriptor_orbit(
|
|
np.rot90(rgb, turn).copy(),
|
|
[np.rot90(m, turn).copy() for m in support],
|
|
model,
|
|
processor,
|
|
)
|
|
checks.append(c4_mean(rotated))
|
|
path = folder / (rec["id"] + ".npz")
|
|
np.savez_compressed(
|
|
path,
|
|
orbit=orbit,
|
|
pooled=mean,
|
|
rotated=np.asarray(checks),
|
|
ids=np.asarray([c["id"] for c in cs]),
|
|
)
|
|
receipts.append(
|
|
dict(id=rec["id"], sha256=sha(path), rgb_sha256=sha(rgb_path), candidates=len(cs))
|
|
)
|
|
print(json.dumps(dict(completed=i + 1, total=len(records))), flush=True)
|
|
save_new(
|
|
root / "features.json",
|
|
dict(
|
|
**timestamp(),
|
|
source_sha256=sha(Path(__file__)),
|
|
candidates_sha256=sha(root / "candidates.json"),
|
|
records=receipts,
|
|
max_gpu_bytes=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"]
|
|
receipt = json.loads((root / "features.json").read_text())
|
|
assert receipt["source_sha256"] == sha(Path(__file__))
|
|
assert receipt["candidates_sha256"] == sha(root / "candidates.json")
|
|
data = {}
|
|
for rec in records:
|
|
rid = rec["id"]
|
|
path = root / "features" / (rid + ".npz")
|
|
assert sha(path) == next(a["sha256"] for a in receipt["records"] if a["id"] == rid)
|
|
z = np.load(path)
|
|
cs = rec["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)
|
|
assert np.array_equal(c4_mean(z["orbit"]), z["pooled"])
|
|
data[rid] = dict(
|
|
handcrafted14=hand,
|
|
single512=z["orbit"][0],
|
|
c4_512=z["pooled"],
|
|
c4_fused=np.concatenate([hand, z["pooled"]], axis=1),
|
|
)
|
|
return records, review, data
|
|
|
|
|
|
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 protocol["regularization"]:
|
|
scores, folds = {}, {}
|
|
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 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 = [a for a in records if a["split"] == cohort]
|
|
baseline = evaluation(rows, review, predict(rows, data, "handcrafted14", old), 0.15)
|
|
variants = {}
|
|
for variant, arm in frozen["variants"].items():
|
|
if arm["selected"] is None:
|
|
continue
|
|
out = evaluation(
|
|
rows,
|
|
review,
|
|
predict(rows, data, variant, arm["model"]),
|
|
arm["selected"]["threshold"],
|
|
)
|
|
variants[variant] = dict(**out, gate_vs_frozen=transfer_gate(baseline, out))
|
|
for out in variants.values():
|
|
out["gate_vs_single"] = (
|
|
transfer_gate(variants["single512"], out) if "single512" in variants else None
|
|
)
|
|
ceiling = evaluation(
|
|
rows, review, {a["id"]: [1.0] * len(a["variants"]["retained"]) for a in rows}, 0.0
|
|
)
|
|
results[cohort] = dict(baseline=baseline, variants=variants, ceiling=ceiling)
|
|
checks = []
|
|
for rec in records:
|
|
z = np.load(root / "features" / (rec["id"] + ".npz"))
|
|
assert all(
|
|
np.array_equal(c4_mean(np.roll(z["orbit"], k, axis=0)), z["pooled"]) for k in range(4)
|
|
)
|
|
for turn, rotated in enumerate(z["rotated"], 1):
|
|
for variant in ["c4_512", "c4_fused"]:
|
|
arm = frozen["variants"][variant]
|
|
if arm["selected"] is None:
|
|
continue
|
|
x = (
|
|
rotated
|
|
if variant == "c4_512"
|
|
else np.concatenate([data[rec["id"]]["handcrafted14"], rotated], axis=1)
|
|
)
|
|
a = probability(data[rec["id"]][variant], arm["model"])
|
|
b = probability(x, arm["model"])
|
|
threshold = arm["selected"]["threshold"]
|
|
error = float(np.max(np.abs(a - b))) if len(a) else 0.0
|
|
checks.append(
|
|
dict(
|
|
id=rec["id"],
|
|
turn=turn,
|
|
variant=variant,
|
|
descriptor_max_error=float(np.max(np.abs(rotated - z["pooled"]))),
|
|
score_max_error=error,
|
|
accepted_identical=bool(np.array_equal(a >= threshold, b >= threshold)),
|
|
passed=error <= 1e-5
|
|
and bool(np.array_equal(a >= threshold, b >= threshold)),
|
|
)
|
|
)
|
|
save_new(
|
|
root / "results.json",
|
|
dict(
|
|
**timestamp(),
|
|
chosen=frozen["chosen"],
|
|
models_sha256=sha(root / "models-frozen.json"),
|
|
cohorts=results,
|
|
invariance=dict(
|
|
cyclic_permutations_bitexact=len(records),
|
|
independently_recomputed=checks,
|
|
passed=all(x["passed"] for x in checks),
|
|
),
|
|
),
|
|
)
|
|
print(
|
|
json.dumps(
|
|
{
|
|
k: dict(
|
|
baseline=v["baseline"]["summary"],
|
|
variants={
|
|
n: dict(**a["summary"], gate=a["gate_vs_frozen"])
|
|
for n, a in v["variants"].items()
|
|
},
|
|
ceiling=v["ceiling"]["summary"],
|
|
)
|
|
for k, v in results.items()
|
|
}
|
|
)
|
|
)
|
|
print("invariance", checks)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
{"extract": extract, "train": train, "evaluate": evaluate}[sys.argv[1]](Path(sys.argv[2]))
|