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:
DCCONSTRUCTIONS
2026-10-29 09:10:00 +03:00
parent 69dc566665
commit 25dc0a1b44
128 changed files with 23742 additions and 0 deletions
@@ -0,0 +1,515 @@
"""Pinned, task-specific supervision over a frozen review corpus (Worker only).
Explicit reviewed pixel runs and source-vector ranges; no automatic rasterization
of edited geometry, inferred background, label fitting or media copying.
"""
import argparse
import json
import math
import shutil
import tempfile
from datetime import datetime
from pathlib import Path, PurePosixPath
from corpus_store import Corpus, checked_file, load_json, sha256
from dataset_store import checksum, confined, digest, write
PLAN_SCHEMA = "missioncore.semantic-admission-plan/v1"
DECISION_SCHEMA = "missioncore.semantic-admission-decision/v1"
SCHEMA = "missioncore.semantic-supervision/v1"
TASKS = {"observed_paint", "contextual_map"}
MAX_RECORD = 2 * 1024**2
MAX_RELEASE = 64 * 1024**2
MAX_DECISIONS = 2048
MAX_PIXELS = 4 * 1024**2
def text(value):
if not isinstance(value, str) or not value.strip() or len(value) > 2048:
raise ValueError("Explicit bounded review text required")
return value
def keys(value, expected):
if not isinstance(value, dict) or set(value) != set(expected.split()):
raise ValueError("Unsupported or missing review fields")
def bounded(value):
if len(json.dumps(value, allow_nan=False).encode()) > MAX_RECORD:
raise ValueError("Review record budget exceeded")
return value
def revision_policy(rows):
if not isinstance(rows, list) or not 1 <= len(rows) <= MAX_DECISIONS:
raise ValueError("Explicit selected source revisions required")
result = {}
for row in rows:
keys(row, "world_sha256 revision annotation_sha256")
for value in row.values():
sha256(value)
world = row["world_sha256"]
if world in result:
raise ValueError("Select exactly one annotation revision per source world")
result[world] = row
return result
def selected(reference, policy):
source = reference["source"]
identity = {k: source[k] for k in ("world_sha256", "revision", "annotation_sha256")}
if policy.get(identity["world_sha256"]) != identity:
raise ValueError("Sample does not belong to the selected annotation revision")
def view_key(value):
keys(value, "sample_id view")
sha256(value["sample_id"])
name = text(value["view"])
if PurePosixPath(name).name != name or any(c in name for c in "\\:"):
raise ValueError("Unsafe view identity")
return value["sample_id"], name
def input_view(corpus, anchor, value, policy, verify_media):
sample_id, view = view_key(value)
reference = corpus.reference(sample_id)
selected(reference, policy)
if any(reference[k] != anchor[k] for k in ("source", "physical_group", "split")):
raise ValueError("Context must share source revision, physical group and split")
folder = PurePosixPath(reference["sample"]).parent
camera_name, rgb_name = str(folder / "cameras.json"), str(folder / (view + ".png"))
with corpus.open_member(reference, camera_name) as stream:
raw = stream.read(MAX_RECORD + 1)
if len(raw) > MAX_RECORD:
raise ValueError("Camera metadata budget exceeded")
cameras = json.loads(raw)
matches = [c for c in cameras["views"] if c["id"] == view]
if len(matches) != 1 or rgb_name not in reference["members"]:
raise ValueError("Input must bind exactly one raw view and camera")
camera = matches[0]
dimensions(camera["size"])
if verify_media:
with corpus.open_member(reference, rgb_name):
pass # Checks bytes; does not decode or copy the image.
return dict(
sample_id=sample_id,
view=view,
rgb=dict(name=rgb_name, **reference["members"][rgb_name]),
camera=camera,
camera_sha256=digest(camera),
cameras_member=dict(name=camera_name, **reference["members"][camera_name]),
coordinates=text(cameras["coordinates"]),
pixel_convention=text(cameras["pixel_convention"]),
)
def dimensions(size):
if (
not isinstance(size, list)
or len(size) != 2
or any(type(v) is not int or v <= 0 for v in size)
or size[0] * size[1] > MAX_PIXELS
):
raise ValueError("Invalid or oversized review raster")
return size
def pixel_runs(value, size):
"""Integer image indices: [row, first_column, exclusive_end_column]."""
width, height = dimensions(size)
occupied = []
for kind in ("paint", "background", "unknown"):
runs = value[kind]
if not isinstance(runs, list) or runs != sorted(runs):
raise ValueError("Pixel runs must be ordered")
for run in runs:
if (
not isinstance(run, list)
or len(run) != 3
or any(type(v) is not int for v in run)
or not 0 <= run[0] < height
or not 0 <= run[1] < run[2] <= width
):
raise ValueError("Pixel run outside its declared view")
occupied.append(run)
occupied.sort()
if any(a[0] == b[0] and a[2] > b[1] for a, b in zip(occupied, occupied[1:], strict=False)):
raise ValueError("Conflicting or duplicated reviewed pixels")
return {k: value[k] for k in ("paint", "background", "unknown")}
def pixel_target(view):
"""One loss target: 255 ignore, 0 explicit background, 1 observed paint.
No class is assigned to the complement of the reviewed runs. This bytearray
is generated on demand; a trainer must preserve ignore_index=255.
"""
width, height = dimensions(view["size"])
runs = pixel_runs(view, view["size"])
target = bytearray([255]) * (width * height)
for kind, label in (("paint", 1), ("background", 0)):
for row, start, end in runs[kind]:
target[row * width + start : row * width + end] = bytes([label]) * (end - start)
return target
def fragments(feature, ranges):
"""Preserve exact line segments, selecting only explicitly reviewed intervals."""
geometry = feature["geometry"]
if geometry["type"] not in {"LineString", "Polygon"}:
raise ValueError("Unsupported source vector geometry")
paths = (
[geometry["coordinates"]] if geometry["type"] == "LineString" else geometry["coordinates"]
)
if not isinstance(ranges, list) or not ranges or ranges != sorted(ranges):
raise ValueError("Explicit ordered vector ranges required")
result = []
for span in ranges:
if (
not isinstance(span, list)
or len(span) != 4
or any(type(v) is not int for v in span[:2])
or any(type(v) not in (int, float) or not math.isfinite(v) for v in span[2:])
):
raise ValueError("Invalid vector range")
path, segment, lo, hi = span
if (
not 0 <= path < len(paths)
or not 0 <= segment < len(paths[path]) - 1
or not 0 <= lo < hi <= 1
):
raise ValueError("Vector range outside source geometry")
if feature["properties"].get("editor_curves", {}).get(str(path)):
raise ValueError("Curved paths need an explicit curve-aware target contract")
a, b = paths[path][segment : segment + 2]
if any(
len(p) != 3 or any(type(v) not in (int, float) or not math.isfinite(v) for v in p)
for p in (a, b)
):
raise ValueError("Finite scene-local XYZ required")
if a[:2] == b[:2]:
raise ValueError("Degenerate planar source segment")
result.append(
[
a if lo == 0 else [x + lo * (y - x) for x, y in zip(a, b, strict=True)],
b if hi == 1 else [x + hi * (y - x) for x, y in zip(a, b, strict=True)],
]
)
return result
def compile_decision(corpus, decision, policy, *, verify_media=False):
bounded(decision)
keys(
decision,
"schema_version sample_id reviewer reviewed_utc reason inputs "
"observed_paint contextual_map",
)
if decision["schema_version"] != DECISION_SCHEMA:
raise ValueError("Unsupported admission decision")
keys(decision["reviewer"], "id kind")
text(decision["reviewer"]["id"])
if decision["reviewer"]["kind"] not in {"human", "assistant"}:
raise ValueError("Explicit reviewer kind required; rules are not reviewers")
text(decision["reason"])
stamp = datetime.fromisoformat(decision["reviewed_utc"])
if stamp.tzinfo is None:
raise ValueError("Review time must include a timezone")
reference = corpus.reference(decision["sample_id"])
selected(reference, policy)
if not 1 <= len(decision["inputs"]) <= 16:
raise ValueError("Select one to sixteen bounded context views")
inputs = {}
for value in decision["inputs"]:
key = view_key(value)
if key in inputs:
raise ValueError("Duplicate input view")
inputs[key] = input_view(corpus, reference, value, policy, verify_media)
review = corpus.review(reference)
features = {f["id"]: f for f in review["active_candidates"]}
pixels, vectors, excluded, spans = [], [], [], {}
seen_views = set()
for record in decision["observed_paint"]:
keys(record, "view paint background unknown")
view = text(record["view"])
key = (reference["id"], view)
if key not in inputs or view in seen_views:
raise ValueError("Pixel target needs a unique included source view")
seen_views.add(view)
size = inputs[key]["camera"]["size"]
runs = pixel_runs(record, size)
pixels.append(dict(view=view, size=size, **runs, ignore_index=255))
for record in decision["contextual_map"]:
keys(record, "feature_id geometry_sha256 ranges state evidence support reason")
text(record["reason"])
feature = features.get(record["feature_id"])
if feature is None:
raise ValueError("Unknown or rejected feature cannot become a target")
if digest(feature["geometry"]) != sha256(record["geometry_sha256"]):
raise ValueError("Reviewed source geometry changed")
if record["state"] not in {"confirmed", "weak", "unknown"} or record["evidence"] not in {
"observed",
"context",
"rule",
"unknown",
}:
raise ValueError("Unknown vector evidence or review state")
support = [view_key(v) for v in record["support"]]
if len(support) != len(set(support)) or any(v not in inputs for v in support):
raise ValueError("Every evidence view must be present in model inputs")
if record["state"] == "confirmed" and (
not support or record["evidence"] not in {"observed", "context"}
):
raise ValueError("A rule or unknown evidence cannot confirm a vector target")
coordinates = fragments(feature, record["ranges"])
for path, segment, lo, hi in record["ranges"]:
key = (feature["id"], path, segment)
existing = spans.setdefault(key, [])
if any(max(lo, a) < min(hi, b) for a, b in existing):
raise ValueError("Conflicting or duplicated reviewed vector ranges")
existing.append((lo, hi))
target = dict(
**record,
semantic_class=text(feature["properties"]["class"]),
fragments=coordinates,
completeness="reviewed-ranges-only",
supervised_axes=["x", "y"],
z_supervision=False,
)
(vectors if record["state"] == "confirmed" else excluded).append(target)
return bounded(
dict(
sample_id=reference["id"],
source=reference["source"],
physical_group=reference["physical_group"],
split=reference["split"],
reviewer=decision["reviewer"],
reviewed_utc=decision["reviewed_utc"],
reason=decision["reason"],
inputs=list(inputs.values()),
observed_paint=pixels,
contextual_map=vectors,
excluded_vectors=excluded,
background_from_absence=False,
vector_completeness="reviewed-ranges-only",
)
)
def active(record, task):
if task == "contextual_map":
return bool(record[task])
return any(v["paint"] or v["background"] for v in record[task])
def build(store, plan, destination):
"""Publish a new immutable sidecar; original corpus and datasets stay untouched."""
store = Path(store).resolve()
keys(plan, "schema_version corpus revisions decisions")
if plan["schema_version"] != PLAN_SCHEMA:
raise ValueError("Unsupported admission plan")
policy = revision_policy(plan["revisions"])
destination = confined(store, destination)
if destination.exists():
raise ValueError("Supervision version already exists")
if not 1 <= len(plan["decisions"]) <= MAX_DECISIONS:
raise ValueError("Review release decision budget exceeded")
with Corpus(store, plan["corpus"]["path"], plan["corpus"]["sha256"]) as corpus:
protected = [
corpus.root,
*[confined(store, d["path"]) for d in corpus.manifest["datasets"]],
]
for entry in plan["decisions"]:
keys(entry, "path sha256")
path = confined(store, entry["path"])
if checksum(path) != sha256(entry["sha256"]):
raise ValueError("Pinned review decision changed")
protected.append(path)
if any(destination.is_relative_to(p) or p.is_relative_to(destination) for p in protected):
raise ValueError("Supervision output overlaps immutable input")
destination.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix=".supervision-", dir=destination.parent) as tmp:
stage = Path(tmp)
(stage / "decisions").mkdir()
records, used = {}, 0
geometry_identities = {}
counts = {
s: {t: 0 for t in sorted(TASKS)}
for s in ("train", "validation", "test", "regression")
}
for entry in plan["decisions"]:
source = confined(store, entry["path"])
decision = load_json(source, MAX_RECORD)
if checksum(source) != entry["sha256"]:
raise ValueError("Decision changed during compilation")
compiled = compile_decision(corpus, decision, policy, verify_media=True)
for target in compiled["contextual_map"] + compiled["excluded_vectors"]:
key = (compiled["source"]["world_sha256"], target["feature_id"])
prior = geometry_identities.setdefault(key, target["geometry_sha256"])
if prior != target["geometry_sha256"]:
raise ValueError("Conflicting source geometry across review windows")
identity = compiled["sample_id"]
if identity in records:
raise ValueError("Conflicting decisions for the same sample")
name = f"decisions/{identity}.json"
write(stage / name, decision)
used += (stage / name).stat().st_size
if used > MAX_RELEASE:
raise ValueError("Supervision release byte budget exceeded")
records[identity] = dict(
path=name, compiled_sha256=digest(compiled), split=compiled["split"]
)
for task in TASKS:
counts[compiled["split"]][task] += active(compiled, task)
for name in ("admission_store.py", "corpus_store.py", "dataset_store.py"):
shutil.copyfile(Path(__file__).with_name(name), stage / name)
manifest = dict(
schema_version=SCHEMA,
corpus=plan["corpus"],
revisions=plan["revisions"],
plan_sha256=digest(plan),
records=records,
counts=counts,
files={
p.relative_to(stage).as_posix(): dict(
sha256=checksum(p), bytes=p.stat().st_size
)
for p in sorted(stage.rglob("*"))
if p.is_file()
},
)
if sum(s["bytes"] for s in manifest["files"].values()) > MAX_RELEASE:
raise ValueError("Supervision release byte budget exceeded")
if len(json.dumps(manifest).encode()) > 8 * 1024**2:
raise ValueError("Supervision manifest budget exceeded")
write(stage / "supervision.json", manifest)
destination.mkdir()
try:
for name in [*manifest["files"], "supervision.json"]:
target = destination / name
target.parent.mkdir(exist_ok=True)
(stage / name).replace(target)
except BaseException:
shutil.rmtree(destination)
raise
return dict(
path=destination.relative_to(store).as_posix(),
sha256=checksum(destination / "supervision.json"),
counts=counts,
)
class Supervision:
"""Lazily compile reviewed targets; training access always uses the train split."""
def __init__(self, store, release, expected_sha256):
self.store = Path(store).resolve()
self.root = confined(self.store, release)
if checksum(self.root / "supervision.json") != sha256(expected_sha256):
raise ValueError("Pinned supervision release changed")
self.manifest = load_json(self.root / "supervision.json")
if self.manifest["schema_version"] != SCHEMA:
raise ValueError("Unsupported supervision release")
for name, spec in self.manifest["files"].items():
checked_file(self.root, name, spec)
self.policy = revision_policy(self.manifest["revisions"])
pointer = self.manifest["corpus"]
self.corpus = Corpus(self.store, pointer["path"], pointer["sha256"])
def __enter__(self):
return self
def __exit__(self, *args):
self.corpus.close()
def batches(self, task, split, batch_size=8):
if task not in TASKS:
raise ValueError("Select an explicit supervision task")
batch, size = [], 0
for references in self.corpus.batches(split, batch_size):
for reference in references:
spec = self.manifest["records"].get(reference["id"])
if spec is None:
continue
name = spec["path"]
decision = load_json(
checked_file(self.root, name, self.manifest["files"][name]), MAX_RECORD
)
compiled = compile_decision(self.corpus, decision, self.policy)
if digest(compiled) != spec["compiled_sha256"]:
raise ValueError("Supervision differs from its pinned review")
if not active(compiled, task):
continue
# Consumer sees only this task's targets, not another task's geometry
# disguised as visible paint. Provenance is bookkeeping, not a model input.
example = dict(
sample_id=reference["id"],
source=compiled["source"],
physical_group=compiled["physical_group"],
split=split,
task=task,
inputs=compiled["inputs"],
targets=[v for v in compiled[task] if v["paint"] or v["background"]]
if task == "observed_paint"
else compiled[task],
supervision_scope="reviewed-pixels-only"
if task == "observed_paint"
else "reviewed-vector-ranges-only",
background_from_absence=False,
training_eligible=(split == "train"),
review_sha256=spec["compiled_sha256"],
)
length = len(json.dumps(example).encode())
if length > MAX_RECORD:
raise ValueError("Example metadata budget exceeded")
if batch and (len(batch) >= batch_size or size + length > MAX_RECORD):
yield batch
batch, size = [], 0
batch.append(example)
size += length
if batch:
yield batch
def open_image(self, value):
"""Open a bound raw RGB descriptor from an example, with a fresh hash check."""
reference = self.corpus.reference(value["sample_id"])
selected(reference, self.policy)
view_key({"sample_id": value["sample_id"], "view": value["view"]})
name = str(PurePosixPath(reference["sample"]).parent / (value["view"] + ".png"))
if name not in reference["members"] or value["rgb"] != dict(
name=name, **reference["members"][name]
):
raise ValueError("Input is not the bound raw RGB view")
return self.corpus.open_member(reference, name)
def training_batches(self, task, batch_size=8):
yield from self.batches(task, "train", batch_size)
def main():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
make = commands.add_parser("build")
make.add_argument("store", type=Path)
make.add_argument("plan", type=Path)
make.add_argument("destination")
inspect = commands.add_parser("inspect")
inspect.add_argument("store", type=Path)
inspect.add_argument("release")
inspect.add_argument("sha256")
args = parser.parse_args()
if args.command == "build":
result = build(args.store, load_json(args.plan), args.destination)
else:
with Supervision(args.store, args.release, args.sha256) as reader:
result = dict(
counts=reader.manifest["counts"], tasks=sorted(TASKS), model_trained=False
)
print(json.dumps(result))
if __name__ == "__main__":
main()
@@ -0,0 +1,200 @@
"""Publish source-reviewed agent ROIs only after a terminal root acceptance.
Retains all previous decisions and targets; no live-map or training side effect.
A release is assistant-reviewed TRAIN, never independent evaluation gold.
"""
import copy
from datetime import UTC, datetime
from pathlib import Path
from admission_store import Supervision, build, pixel_target
from agent_cycle import Cycle
from annotation_provenance import audit_unit
from dataset_store import checksum, confined, digest, read, write
from region_coverage import merge, raster_proposal, runs
def publish(store, identity, destination):
store = Path(store).resolve()
controller = Cycle(store)
try:
state = controller.status(identity)
finally:
controller.close()
if state["state"] != "closed" or state["root_review"]["verdict"] != "accepted":
raise ValueError("Root acceptance required before supervision publication")
units = [u for u in state["plan"]["units"] if u["id"] in state["root_review"]["admitted_units"]]
if not units:
raise ValueError("Root did not admit any units")
pointers = {digest(u["payload"]["supervision"]) for u in units}
if len(pointers) != 1:
raise ValueError("One immutable baseline release per iteration required")
pointer = units[0]["payload"]["supervision"]
output = confined(store, destination)
journal = store / "agent-reviews" / identity
if output == journal or output.is_relative_to(journal) or journal.is_relative_to(output):
raise ValueError("Output overlaps decision journal")
proposals = {t["unit"]: t["result"] for t in state["tasks"] if t["stage"] == "annotate"}
audit, decisions, changed = [], {}, set()
with Supervision(store, pointer["path"], pointer["sha256"]) as reader:
if output.is_relative_to(reader.root) or reader.root.is_relative_to(output):
raise ValueError("Output overlaps baseline")
for sample_id, spec in reader.manifest["records"].items():
decisions[sample_id] = read(reader.root / spec["path"])
entries = {e["sample_id"]: e for b in reader.training_batches("observed_paint") for e in b}
merged, explicit_unknown, touched = {}, {}, {}
for unit in units:
p = unit["payload"]
key = (p["sample_id"], p["view"])
e = entries[p["sample_id"]]
if e["split"] != "train" or e["physical_group"] != unit["physical_group"]:
raise ValueError("Physical split changed")
target = next(t for t in e["targets"] if t["view"] == p["view"])
original = pixel_target(target)
protected = bytearray(len(original)) if target["unknown"] else b""
for y, a, b in target["unknown"]:
protected[y * p["size"][0] + a : y * p["size"][0] + b] = bytes([1]) * (b - a)
record = raster_proposal(p, proposals[unit["id"]])
candidate, stats = merge(p, record, original, protected)
width = p["size"][0]
x0, y0, x1, y1 = p["roi"]
pixels = {y * width + x for y in range(y0, y1) for x in range(x0, x1)}
prior = touched.setdefault(key, set())
if prior & pixels:
raise ValueError("Overlapping units require one combined review")
prior.update(pixels)
out = merged.setdefault(key, bytearray(original))
ignored = explicit_unknown.setdefault(key, bytearray(protected or bytes(len(original))))
for i in pixels:
out[i] = candidate[i]
ignored[i] = int(candidate[i] == 255)
audit.append(
dict(
unit=unit["id"],
**stats,
provenance=audit_unit(
p,
record,
original,
candidate,
protected,
merged_sha256=stats["merged_sha256"],
),
)
)
changed.add(p["sample_id"])
for (sample_id, view), out in merged.items():
e = entries[sample_id]
target = next(t for t in e["targets"] if t["view"] == view)
record = runs(out, target["size"], view)
# Keep unreviewed complement ignored without claiming it was reviewed.
mask = bytes(255 if v else 0 for v in explicit_unknown[(sample_id, view)])
record["unknown"] = runs(mask, target["size"], view)["unknown"]
decision = copy.deepcopy(decisions[sample_id])
decision["observed_paint"] = [
record if t["view"] == view else t for t in decision["observed_paint"]
]
# Freeze time once for idempotent publication retries.
decision["reviewer"] = dict(id=state["plan"]["root_actor"], kind="assistant")
decision["reason"] = (
f"Agent iteration {identity}; independent source review + root acceptance; "
f"prior release {pointer['sha256']}; assistant-reviewed TRAIN only."
)
decisions[sample_id] = decision
journal.mkdir(parents=True, exist_ok=True)
immutable(journal / "cycle.json", state)
stamp_path = journal / "publication.json"
stamp = (
read(stamp_path)
if stamp_path.exists()
else dict(
utc=datetime.now(UTC).isoformat(),
iteration=identity,
root_review_sha256=digest(state["root_review"]),
baseline=pointer,
)
)
immutable(stamp_path, stamp)
for sample_id in changed:
decisions[sample_id]["reviewed_utc"] = stamp["utc"]
plan = dict(
schema_version="missioncore.semantic-admission-plan/v1",
corpus=reader.manifest["corpus"],
revisions=reader.manifest["revisions"],
decisions=[],
)
for sample_id, decision in sorted(decisions.items()):
path = journal / f"{sample_id}.json"
immutable(path, decision)
plan["decisions"].append(
dict(path=path.relative_to(store).as_posix(), sha256=checksum(path))
)
publish_audit(
journal,
dict(
iteration=identity,
units=audit,
changed_samples=sorted(changed),
automatic_training=False,
production_eligible=False,
),
)
immutable(journal / "plan.json", plan)
if (output / "supervision.json").exists():
with Supervision(store, destination, checksum(output / "supervision.json")) as existing:
if existing.manifest["plan_sha256"] != digest(plan):
raise ValueError("Destination contains a different release")
return dict(
path=destination,
sha256=checksum(output / "supervision.json"),
counts=existing.manifest["counts"],
)
return build(store, plan, destination)
def immutable(path, value):
if path.exists():
if read(path) != value:
raise ValueError("Published evidence changed")
else:
write(path, value)
def publish_audit(journal, current):
"""Preserve legacy audit bytes on retry; bind additive proof separately."""
path = journal / "audit.json"
sidecar = journal / "audit-provenance-v1.json"
if sidecar.exists():
if not path.exists():
raise ValueError("Provenance sidecar requires its original legacy audit")
# An existing sidecar always requires the original legacy projection and
# exact bytes binding, even if audit.json was replaced with current.
elif not path.exists() or read(path) == current:
immutable(path, current)
return
previous = read(path)
units = previous.get("units") if isinstance(previous, dict) else None
if (
not isinstance(units, list)
or not units
or any(not isinstance(unit, dict) or "provenance" in unit for unit in units)
):
raise ValueError("Published evidence changed")
legacy = dict(
current,
units=[
{key: value for key, value in unit.items() if key != "provenance"}
for unit in current["units"]
],
)
if previous != legacy:
raise ValueError("Published legacy audit differs from exact projection")
immutable(
sidecar,
dict(
schema="missioncore.annotation-provenance-audit/v1",
legacy_audit_sha256=checksum(path),
audit=current,
),
)
+687
View File
@@ -0,0 +1,687 @@
"""Bounded, root-gated annotation workflow; executor is the active Codex session.
Uses separate tables in the Worker learning queue. Never consumes builder jobs,
launches a model, promotes supervision or writes a live map. Actor identities are
assigned by the trusted dispatcher, not supplied by an LLM response. This local
ledger is an orchestration boundary, not an authentication service.
"""
import argparse
import json
import re
import sqlite3
import time
import uuid
from contextlib import contextmanager
from pathlib import Path
from dataset_store import checksum, confined, digest
from region_coverage import validate_packet
SCHEMA = "missioncore.semantic-agent-cycle/v1"
SCHEMA_V2 = "missioncore.semantic-agent-cycle/v2"
MAX_JSON = 2 * 1024**2
MAX_LEDGER_JSON = 128 * 1024**2
MAX_PLAN = 256 * 1024
MAX_RESULT = 48 * 1024
MAX_ROOT_REVIEW = 32 * 1024
def encode(value):
result = json.dumps(value, ensure_ascii=False, sort_keys=True, allow_nan=False)
if len(result.encode()) > MAX_JSON:
raise ValueError("Agent record byte budget exceeded")
return result
def text(value):
if not isinstance(value, str) or not value.strip() or len(value) > 4096:
raise ValueError("Bounded nonempty text required")
return value
def actor_id(value):
if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_./:-]{1,160}", value):
raise ValueError("Bounded canonical actor or unit ID required")
return value
class Cycle:
def __init__(self, root, *, clock=time.time):
self.root, self.clock = Path(root).resolve(), clock
self.root.mkdir(parents=True, exist_ok=True)
self.db = sqlite3.connect(self.root / "queue.sqlite3", timeout=10)
self.db.row_factory = sqlite3.Row
self.db.execute("PRAGMA synchronous=FULL")
self.db.executescript("""
CREATE TABLE IF NOT EXISTS agent_cycles (
id TEXT PRIMARY KEY, plan TEXT NOT NULL, state TEXT NOT NULL,
created REAL NOT NULL, deadline REAL NOT NULL, root_review TEXT);
CREATE TABLE IF NOT EXISTS agent_tasks (
cycle TEXT NOT NULL, unit TEXT NOT NULL, stage TEXT NOT NULL,
state TEXT NOT NULL, attempt INTEGER NOT NULL DEFAULT 0,
token TEXT, actor TEXT, expires REAL, result TEXT, result_sha TEXT,
PRIMARY KEY(cycle, unit, stage));
CREATE TABLE IF NOT EXISTS agent_attempts (
token TEXT PRIMARY KEY, cycle TEXT NOT NULL, unit TEXT NOT NULL,
stage TEXT NOT NULL, actor TEXT NOT NULL, started REAL NOT NULL,
finished REAL, result TEXT, result_sha TEXT, stopped_evidence TEXT);
CREATE TABLE IF NOT EXISTS agent_dispatch_receipts (
token TEXT PRIMARY KEY, executor_ref TEXT NOT NULL,
recorded REAL NOT NULL, evidence TEXT NOT NULL);
""")
def close(self):
self.db.close()
@contextmanager
def transaction(self):
self.db.execute("BEGIN IMMEDIATE")
try:
yield
self.db.commit()
except BaseException:
self.db.rollback()
raise
def pins(self, unit):
for pin in unit["sources"]:
if set(pin) != {"path", "sha256", "bytes"}:
raise ValueError("Exact source pin required")
path = confined(self.root, pin["path"])
if not 0 < pin["bytes"] <= 24 * 1024**2:
raise ValueError("Source byte budget exceeded")
if path.stat().st_size != pin["bytes"] or checksum(path) != pin["sha256"]:
raise ValueError("Pinned source changed")
validate_packet(self.root, unit)
def capacity(self, additional):
used = 0
for table, column in (
("agent_cycles", "plan"),
("agent_cycles", "root_review"),
("agent_tasks", "result"),
("agent_attempts", "result"),
("agent_dispatch_receipts", "executor_ref"),
("agent_dispatch_receipts", "evidence"),
):
used += self.db.execute(
f"SELECT COALESCE(SUM(length(CAST({column} AS BLOB))),0) FROM {table}"
).fetchone()[0]
if used + additional > MAX_LEDGER_JSON:
raise ValueError("Agent evidence quota reached; archive closed cycles first")
@staticmethod
def fingerprint(plan):
units = [
dict(
group=u["physical_group"],
payload=u["payload"],
sources=sorted(p["sha256"] for p in u["sources"]),
)
for u in plan["units"]
]
return digest(
dict(
recipe=plan["recipe"],
baseline=plan["baseline_sha256"],
units=sorted(units, key=digest),
)
)
def begin(self, plan):
encoded, identity = encode(plan), digest(plan)
if len(encoded.encode()) > MAX_PLAN:
raise ValueError("Plan byte budget exceeded")
version = plan.get("schema_version")
if set(plan) != {
"schema_version",
"root_actor",
"objective",
"baseline_sha256",
"recipe",
"acceptance",
"limits",
"units",
"parent",
} | ({"objective_contract"} if version == SCHEMA_V2 else set()) or version not in {
SCHEMA,
SCHEMA_V2,
}:
raise ValueError("Unsupported agent plan")
for key in ("root_actor", "objective", "baseline_sha256", "recipe", "acceptance"):
text(plan[key])
actor_id(plan["root_actor"])
limits = plan["limits"]
ceilings = dict(parallel=3, attempts=2, dispatches=48, seconds=86400, lease_seconds=3600)
if set(limits) != set(ceilings) or any(
type(limits[k]) is not int or not 1 <= limits[k] <= cap for k, cap in ceilings.items()
):
raise ValueError("Invalid bounded limits")
if limits["lease_seconds"] > limits["seconds"]:
raise ValueError("Lease exceeds iteration deadline")
units = plan["units"]
if not 1 <= len(units) <= 12 or len({u["id"] for u in units}) != len(units):
raise ValueError("One to twelve unique units required")
for unit in units:
if set(unit) != {"id", "physical_group", "split", "sources", "payload"}:
raise ValueError("Invalid unit packet")
actor_id(unit["id"])
text(unit["physical_group"])
if unit["split"] != "train" or not 1 <= len(unit["sources"]) <= 16:
raise ValueError("Pilot accepts only pinned TRAIN evidence")
self.pins(unit)
if version == SCHEMA_V2:
contract = plan["objective_contract"]
if not isinstance(contract, dict) or set(contract) != {
"deliverable",
"min_admitted_units",
"required_checks",
}:
raise ValueError("Explicit annotation objective contract required")
text(contract["deliverable"])
target, checks = contract["min_admitted_units"], contract["required_checks"]
if type(target) is not int or not 1 <= target <= len(units):
raise ValueError("Objective target must be feasible for planned units")
if limits["dispatches"] < 2 * target:
raise ValueError("Dispatch budget cannot satisfy annotation and review target")
if not isinstance(checks, list) or not 1 <= len(checks) <= 12:
raise ValueError("One to twelve frozen objective checks required")
for check in checks:
actor_id(check)
if len(set(checks)) != len(checks):
raise ValueError("Unique objective checks required")
if limits["parallel"] > 2:
raise ValueError("V2 permits at most two active executors")
now = self.clock()
with self.transaction():
old = self.db.execute("SELECT id FROM agent_cycles WHERE id=?", (identity,)).fetchone()
if old:
return identity
if self.db.execute("SELECT 1 FROM agent_cycles WHERE state!='closed'").fetchone():
raise ValueError("Root must close the current iteration first")
parent = plan["parent"]
latest = self.db.execute(
"SELECT * FROM agent_cycles ORDER BY created DESC, rowid DESC LIMIT 1"
).fetchone()
if latest:
review = json.loads(latest["root_review"])
if parent != latest["id"] or review["next"] == "stop":
raise ValueError("Successor needs the latest root continuation")
old_plan = json.loads(latest["plan"])
if self.fingerprint(plan) == self.fingerprint(old_plan):
raise ValueError("No progress: revise evidence or recipe before retrying")
elif parent is not None:
raise ValueError("Unknown parent")
self.capacity(len(encoded.encode()))
self.db.execute(
"INSERT INTO agent_cycles VALUES(?,?,?,?,?,NULL)",
(identity, encoded, "running", now, now + limits["seconds"]),
)
self.db.executemany(
"INSERT INTO agent_tasks(cycle,unit,stage,state) VALUES(?,?,?,?)",
[(identity, u["id"], "annotate", "ready") for u in units],
)
return identity
def _cycle(self, identity):
row = self.db.execute("SELECT * FROM agent_cycles WHERE id=?", (identity,)).fetchone()
if row is None:
raise ValueError("Unknown iteration")
return row, json.loads(row["plan"])
def _settle(self, identity):
row, plan = self._cycle(identity)
if row["state"] == "closed":
return
now = self.clock()
self.db.execute(
"UPDATE agent_tasks SET state='interrupted' "
"WHERE cycle=? AND state='active' AND expires<=?",
(identity, now),
)
dispatched = self.db.execute(
"SELECT COUNT(*) FROM agent_attempts WHERE cycle=?", (identity,)
).fetchone()[0]
if now >= row["deadline"] or dispatched >= plan["limits"]["dispatches"]:
self.db.execute(
"UPDATE agent_tasks SET state='blocked' WHERE cycle=? AND state='ready'",
(identity,),
)
if now >= row["deadline"]:
self.db.execute(
"UPDATE agent_tasks SET state='interrupted' WHERE cycle=? AND state='active'",
(identity,),
)
pending = self.db.execute(
"SELECT 1 FROM agent_tasks WHERE cycle=? AND state IN ('ready','active')", (identity,)
).fetchone()
self.db.execute(
"UPDATE agent_cycles SET state=? WHERE id=?",
("running" if pending else "root_pending", identity),
)
def claim(self, identity, unit_id, stage, actor):
actor_id(actor)
with self.transaction():
self._settle(identity)
now = self.clock()
row, plan = self._cycle(identity)
if row["state"] != "running":
raise ValueError("Iteration is waiting for root")
task = self.db.execute(
"SELECT * FROM agent_tasks WHERE cycle=? AND unit=? AND stage=?",
(identity, unit_id, stage),
).fetchone()
if task is None or task["state"] != "ready":
raise ValueError("Task is not claimable")
if plan["schema_version"] == SCHEMA_V2:
if self._unconfirmed_handoffs(identity):
raise ValueError("Confirm outstanding handoff or reconcile it before claiming")
if (
stage == "annotate"
and self.db.execute(
"SELECT 1 FROM agent_tasks WHERE cycle=? "
"AND stage='review' AND state='ready'",
(identity,),
).fetchone()
):
raise ValueError("Ready reviews must be dispatched before another author")
active = self.db.execute(
"SELECT COUNT(*) FROM agent_tasks WHERE state IN ('active','interrupted')"
).fetchone()[0]
if active >= plan["limits"]["parallel"]:
raise ValueError("Global agent concurrency exhausted")
if stage == "review":
author = self.db.execute(
"SELECT actor FROM agent_tasks WHERE cycle=? AND unit=? AND stage='annotate'",
(identity, unit_id),
).fetchone()[0]
if actor == author:
raise ValueError("Author cannot review their own proposal")
unit = next(u for u in plan["units"] if u["id"] == unit_id)
self.pins(unit)
now = self.clock()
if now >= row["deadline"]:
raise ValueError("Iteration deadline passed during input verification")
token = uuid.uuid4().hex
expires = min(now + plan["limits"]["lease_seconds"], row["deadline"])
self.db.execute(
"UPDATE agent_tasks SET state='active',attempt=attempt+1,token=?,actor=?,expires=? "
"WHERE cycle=? AND unit=? AND stage=?",
(token, actor, expires, identity, unit_id, stage),
)
self.db.execute(
"INSERT INTO agent_attempts(token,cycle,unit,stage,actor,started) "
"VALUES(?,?,?,?,?,?)",
(token, identity, unit_id, stage, actor, now),
)
packet = dict(
cycle=identity, unit=unit, stage=stage, token=token, actor=actor, expires=expires
)
if stage == "review":
proposal = self.db.execute(
"SELECT result,result_sha FROM agent_tasks "
"WHERE cycle=? AND unit=? AND stage='annotate'",
(identity, unit_id),
).fetchone()
packet.update(proposal=json.loads(proposal[0]), proposal_sha256=proposal[1])
return packet
def _unconfirmed_handoffs(self, identity):
return [
dict(row)
for row in self.db.execute(
"SELECT t.token,t.unit,t.stage,t.actor,t.expires FROM agent_tasks t "
"LEFT JOIN agent_dispatch_receipts d ON d.token=t.token "
"WHERE t.cycle=? AND t.state IN ('active','interrupted') AND d.token IS NULL "
"ORDER BY t.unit,t.stage",
(identity,),
)
]
def confirm_dispatch(self, token, root_actor, executor_ref, evidence):
"""Record a real handoff after sending; absence never proves no executor exists."""
actor_id(executor_ref)
text(evidence)
with self.transaction():
attempt = self.db.execute(
"SELECT * FROM agent_attempts WHERE token=?", (token,)
).fetchone()
if attempt is None:
raise ValueError("Unknown claim")
row, plan = self._cycle(attempt["cycle"])
if root_actor != plan["root_actor"] or plan["schema_version"] != SCHEMA_V2:
raise ValueError("V2 root dispatch confirmation required")
previous = self.db.execute(
"SELECT * FROM agent_dispatch_receipts WHERE token=?", (token,)
).fetchone()
if previous:
if (previous["executor_ref"], previous["evidence"]) != (executor_ref, evidence):
raise ValueError("Conflicting dispatch receipt")
return dict(previous)
task = self.db.execute("SELECT * FROM agent_tasks WHERE token=?", (token,)).fetchone()
if (
task is None
or task["state"] not in {"active", "interrupted", "done"}
or (row["state"] == "closed" and task["state"] != "done")
):
raise ValueError("Cannot confirm a closed or superseded handoff")
self.capacity(len(executor_ref.encode()) + len(evidence.encode()))
recorded = self.clock()
self.db.execute(
"INSERT INTO agent_dispatch_receipts VALUES(?,?,?,?)",
(token, executor_ref, recorded, evidence),
)
return dict(
token=token, executor_ref=executor_ref, recorded=recorded, evidence=evidence
)
def complete(self, token, actor, result):
encoded, sha = encode(result), digest(result)
if len(encoded.encode()) > MAX_RESULT:
raise ValueError("Result byte budget exceeded")
with self.transaction():
attempt = self.db.execute(
"SELECT * FROM agent_attempts WHERE token=?", (token,)
).fetchone()
if attempt is None or attempt["actor"] != actor:
raise ValueError("Claim ownership mismatch")
if attempt["result"] is not None:
if attempt["result_sha"] != sha:
raise ValueError("Changed duplicate completion")
return sha
identity, unit_id, stage = (attempt[k] for k in ("cycle", "unit", "stage"))
row, plan = self._cycle(identity)
task = self.db.execute(
"SELECT * FROM agent_tasks WHERE cycle=? AND unit=? AND stage=?",
(identity, unit_id, stage),
).fetchone()
if (
row["state"] == "closed"
or task["token"] != token
or task["state"] != "active"
or self.clock() >= min(task["expires"], row["deadline"])
):
raise ValueError("Expired or superseded claim; root must reconcile executor")
self.pins(next(u for u in plan["units"] if u["id"] == unit_id))
text(result.get("reason"))
if stage == "review":
proposal = self.db.execute(
"SELECT result_sha FROM agent_tasks "
"WHERE cycle=? AND unit=? AND stage='annotate'",
(identity, unit_id),
).fetchone()[0]
if result.get("proposal_sha256") != proposal or result.get("verdict") not in {
"accept",
"reject",
}:
raise ValueError("Review must bind the exact proposal")
self.capacity(2 * len(encoded.encode()))
now = self.clock()
if now >= min(task["expires"], row["deadline"]):
raise ValueError(
"Claim expired during result validation; root must reconcile executor"
)
self.db.execute(
"UPDATE agent_attempts SET finished=?,result=?,result_sha=? WHERE token=?",
(now, encoded, sha, token),
)
self.db.execute(
"UPDATE agent_tasks SET state='done',result=?,result_sha=? WHERE token=?",
(encoded, sha, token),
)
if stage == "annotate":
self.db.execute(
"INSERT INTO agent_tasks(cycle,unit,stage,state) VALUES(?,?,'review','ready')",
(identity, unit_id),
)
self._settle(identity)
return sha
def reconcile(self, token, root_actor, stopped_evidence, *, retry=False):
"""Trusted root verifies executor termination BEFORE releasing reservation."""
text(stopped_evidence)
with self.transaction():
task = self.db.execute("SELECT * FROM agent_tasks WHERE token=?", (token,)).fetchone()
if task is None:
raise ValueError("Unknown claim")
row, plan = self._cycle(task["cycle"])
if root_actor != plan["root_actor"] or row["state"] == "closed":
raise ValueError("Root reconciliation required")
if task["state"] not in {"active", "interrupted"}:
raise ValueError("Only unfinished executor may be reconciled")
count = self.db.execute(
"SELECT COUNT(*) FROM agent_attempts WHERE cycle=?", (task["cycle"],)
).fetchone()[0]
allowed = (
task["attempt"] < plan["limits"]["attempts"]
and count < plan["limits"]["dispatches"]
and self.clock() < row["deadline"]
)
if retry and not allowed:
raise ValueError("Retry budget exhausted")
self.db.execute(
"UPDATE agent_attempts SET finished=?,stopped_evidence=? WHERE token=?",
(self.clock(), stopped_evidence, token),
)
self.db.execute(
"UPDATE agent_tasks SET state=?,token=NULL WHERE token=?",
("ready" if retry else "blocked", token),
)
self._settle(task["cycle"])
def cancel_ready(self, identity, root_actor, reason):
"""Root cancels undispatched work without releasing executor reservations."""
text(reason)
result = dict(reason=reason, disposition="cancelled_by_root")
encoded, sha = encode(result), digest(result)
with self.transaction():
row, plan = self._cycle(identity)
if root_actor != plan["root_actor"] or row["state"] == "closed":
raise ValueError("Root cancellation requires an open iteration")
count = self.db.execute(
"SELECT COUNT(*) FROM agent_tasks WHERE cycle=? AND state='ready'",
(identity,),
).fetchone()[0]
if count:
self.capacity(count * len(encoded.encode()))
self.db.execute(
"UPDATE agent_tasks SET state='blocked',result=?,result_sha=? "
"WHERE cycle=? AND state='ready'",
(encoded, sha, identity),
)
self._settle(identity)
return dict(cancelled=count)
def status(self, identity):
with self.transaction():
return self._status(identity)
def _status(self, identity):
"""Read settled state while the caller holds the transaction."""
self._settle(identity)
row, plan = self._cycle(identity)
tasks = [
dict(r)
for r in self.db.execute(
"SELECT * FROM agent_tasks WHERE cycle=? ORDER BY unit,stage", (identity,)
)
]
for task in tasks:
if task["result"]:
task["result"] = json.loads(task["result"])
sample = min((u["id"] for u in plan["units"]), key=lambda u: digest([identity, u]))
flagged = sorted(
{
t["unit"]
for t in tasks
if t["state"] != "done"
or (t["stage"] == "review" and t["result"]["verdict"] == "reject")
}
)
snapshot = dict(
id=identity,
state=row["state"],
plan=plan,
tasks=tasks,
root_required_units=sorted({sample, *flagged}),
dispatches=self.db.execute(
"SELECT COUNT(*) FROM agent_attempts WHERE cycle=?", (identity,)
).fetchone()[0],
root_review=json.loads(row["root_review"]) if row["root_review"] else None,
)
if plan["schema_version"] == SCHEMA_V2:
review = snapshot["root_review"] or {}
snapshot.update(
unconfirmed_handoffs=self._unconfirmed_handoffs(identity),
ready_tasks=[
dict(unit=t["unit"], stage=t["stage"])
for t in sorted(
(t for t in tasks if t["state"] == "ready"),
key=lambda t: (t["stage"] != "review", t["unit"]),
)
],
progress=dict(
planned=len(plan["units"]),
proposed=sum(t["stage"] == "annotate" and t["state"] == "done" for t in tasks),
reviewed=sum(t["stage"] == "review" and t["state"] == "done" for t in tasks),
review_accepted=sum(
t["stage"] == "review"
and t["state"] == "done"
and t["result"]["verdict"] == "accept"
for t in tasks
),
admitted=len(review.get("admitted_units", [])),
blocked=sum(t["state"] == "blocked" for t in tasks),
unreconciled=sum(t["state"] == "interrupted" for t in tasks),
target=plan["objective_contract"]["min_admitted_units"],
objective_outcome=review.get("objective_outcome"),
),
)
return snapshot
def decide(self, identity, actor, review):
encoded = encode(review)
if len(encoded.encode()) > MAX_ROOT_REVIEW:
raise ValueError("Root review byte budget exceeded")
with self.transaction():
snapshot = self._status(identity)
plan = snapshot["plan"]
if actor != plan["root_actor"] or snapshot["state"] != "root_pending":
raise ValueError("Root decision only at terminal iteration")
if any(t["state"] == "interrupted" for t in snapshot["tasks"]):
raise ValueError("Unconfirmed executors still reserve resources")
if (
set(review)
!= {
"verdict",
"next",
"reason",
"inspected_units",
"admitted_units",
"checks",
"tuning",
}
| (
{"objective_outcome", "objective_checks", "outcome_reason", "remaining_work"}
if plan["schema_version"] == SCHEMA_V2
else set()
)
or review["verdict"] not in {"accepted", "rejected"}
or review["next"] not in {"continue", "revise", "stop"}
):
raise ValueError("Explicit root verdict and next action required")
text(review["reason"])
text(review["tuning"])
if plan["schema_version"] == SCHEMA_V2:
contract, checks = plan["objective_contract"], review["objective_checks"]
outcome = review["objective_outcome"]
if (
outcome not in {"achieved", "not_achieved", "inconclusive"}
or not isinstance(checks, dict)
or set(checks) != set(contract["required_checks"])
or any(type(v) is not bool for v in checks.values())
):
raise ValueError("Exact frozen objective checks and outcome required")
text(review["outcome_reason"])
remaining = review["remaining_work"]
if not isinstance(remaining, list) or len(remaining) > 12:
raise ValueError("Bounded remaining work required")
for item in remaining:
text(item)
if outcome == "achieved":
if (
review["verdict"] != "accepted"
or not all(checks.values())
or len(review["admitted_units"]) < contract["min_admitted_units"]
or remaining
):
raise ValueError("Objective target/checks not achieved")
elif not remaining:
raise ValueError("Unmet objective needs remaining work or blocker")
if not set(snapshot["root_required_units"]).issubset(review["inspected_units"]):
raise ValueError("Inspect flagged and preselected units")
admitted = review["admitted_units"]
if not isinstance(admitted, list) or len(set(admitted)) != len(admitted):
raise ValueError("Unique admitted unit list required")
approved = {
t["unit"]
for t in snapshot["tasks"]
if t["stage"] == "review"
and t["state"] == "done"
and t["result"]["verdict"] == "accept"
}
if review["verdict"] == "accepted":
if (
not admitted
or not set(admitted).issubset(approved)
or not review["checks"]
or any(v is not True for v in review["checks"].values())
):
raise ValueError("Cannot accept failed or incomplete evidence")
for unit in plan["units"]:
self.pins(unit)
elif admitted or review["next"] == "continue":
raise ValueError("Rejected iteration cannot admit units or continue unchanged")
self.capacity(len(encoded.encode()))
self.db.execute(
"UPDATE agent_cycles SET state='closed',root_review=? WHERE id=?",
(encoded, identity),
)
return digest(review)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--store", required=True)
parser.add_argument(
"action",
choices=[
"begin",
"status",
"claim",
"confirm_dispatch",
"complete",
"reconcile",
"cancel_ready",
"decide",
],
)
parser.add_argument(
"--request", required=True, help="Bounded JSON arguments; actor assigned by dispatcher"
)
args = parser.parse_args()
path = Path(args.request)
if path.stat().st_size > MAX_JSON:
raise ValueError("Request too large")
request = json.loads(path.read_text(encoding="utf-8"))
cycle = Cycle(args.store)
try:
print(encode(getattr(cycle, args.action)(**request)))
finally:
cycle.close()
if __name__ == "__main__":
main()
@@ -0,0 +1,83 @@
"""Pinned source-reviewed label withdrawal; no class inference or model input."""
import hashlib
import math
import numpy as np
from PIL import Image, ImageDraw
def withdraw_labels(sample, review, target):
if (
review["name"] != sample["name"]
or review["input_sha256"] != sample["input"]["rgb"]["sha256"]
):
raise ValueError("Pinned raw input required")
if (
target.dtype != np.uint8
or target.ndim != 2
or list(target.shape[::-1]) != sample["size"]
or not np.isin(target, [0, 1, 255]).all()
):
raise ValueError("Aligned uint8 target required")
actual = hashlib.sha256(target.tobytes()).hexdigest()
if actual != sample["target_sha256"] or review["target_sha256"] != actual:
raise ValueError("Pinned target changed")
expected = {c["id"]: c["sha256"] for c in sample["components"]}
if review["reviewed_components"] != expected or not review["raw_first"]:
raise ValueError("Complete raw-first component review required")
if not isinstance(review["reason"], str) or not review["reason"].strip():
raise ValueError("Explicit visual evidence required")
zones = review["withdrawals"]
if not isinstance(zones, list) or len(zones) > 64:
raise ValueError("Bounded explicit withdrawal zones required")
changed = np.zeros(target.shape, dtype=bool)
ids, counts = set(), []
width, height = sample["size"]
for zone in zones:
if (
not isinstance(zone["id"], str)
or not zone["id"]
or zone["id"] in ids
or type(zone["label"]) is not int
or zone["label"] not in (0, 1)
or not isinstance(zone["reason"], str)
or not zone["reason"].strip()
):
raise ValueError("Unique zone, old class and visual reason required")
ids.add(zone["id"])
polygon = zone["polygon"]
if not isinstance(polygon, list) or not 3 <= len(polygon) <= 16:
raise ValueError("Explicit bounded native-pixel polygon required")
for point in polygon:
if (
not isinstance(point, list)
or len(point) != 2
or any(type(v) not in (int, float) or not math.isfinite(v) for v in point)
or not 0 <= point[0] < width
or not 0 <= point[1] < height
):
raise ValueError("Polygon outside native image")
canvas = Image.new("1", (width, height))
ImageDraw.Draw(canvas).polygon([tuple(p) for p in polygon], fill=1)
part = np.asarray(canvas, dtype=bool) & (target == zone["label"])
if not part.any():
raise ValueError("Withdrawal must touch explicit known labels")
counts.append(
dict(
id=zone["id"],
label=zone["label"],
selected=int(part.sum()),
newly_withdrawn=int((part & ~changed).sum()),
)
)
changed |= part
revised = target.copy()
revised[changed] = 255
return revised, dict(
zones=counts,
removed_paint=int((changed & (target == 1)).sum()),
removed_background=int((changed & (target == 0)).sum()),
target_sha256=actual,
revised_sha256=hashlib.sha256(revised.tobytes()).hexdigest(),
)
@@ -0,0 +1,147 @@
"""Read-only provenance proof for a reviewed ROI; never infer legacy subtypes.
The sidecar describes annotation mechanics, not semantic truth. A zero source-
unknown count is meaningful only when source_subtypes_known is true.
"""
import hashlib
from admission_store import pixel_runs
from dataset_store import digest
from region_coverage import roi_bounds
def sha(value):
return hashlib.sha256(value).hexdigest()
def _mask(spans, width, count):
mask = bytearray(count)
for y, a, b in spans:
mask[y * width + a : y * width + b] = bytes([1]) * (b - a)
return mask
def _difference(spans, mask, width):
result = []
for y, a, b in spans:
start = None
for x in range(a, b):
keep = not mask[y * width + x]
if keep and start is None:
start = x
if not keep and start is not None:
result.append([y, start, x])
start = None
if start is not None:
result.append([y, start, b])
return result
def audit_unit(packet, record, original, merged, protected=b"", *, merged_sha256):
"""Validate exact source->merged mechanics and return additive JSON evidence.
Prior protected RLE has no trustworthy subtype; it stays explicitly untyped.
Missing source_unknown likewise makes this record's unknown untyped. Outside
this ROI, original 255 without prior protection is unassigned to this review.
The caller still owns source/media binding and independent semantic review.
"""
size = packet["size"]
x0, y0, x1, y1 = roi_bounds(size, packet["roi"])
width, height = size
count = width * height
if any(not isinstance(v, (bytes, bytearray)) for v in (original, merged, protected)):
raise ValueError("Native byte targets and protected mask required")
if any(len(v) != count or set(v) - {0, 1, 255} for v in (original, merged)):
raise ValueError("Aligned ternary native targets required")
if sha(original) != packet["target_sha256"] or sha(merged) != merged_sha256:
raise ValueError("Target SHA mismatch")
if protected and (len(protected) != count or set(protected) - {0, 1}):
raise ValueError("Aligned binary protected mask required")
if sha(protected) != packet["protected_sha256"]:
raise ValueError("Protected SHA mismatch")
if record["view"] != packet["view"]:
raise ValueError("Source view mismatch")
checked = pixel_runs(record, size)
labels = bytearray([3]) * count # 3 = not reviewed; never a class or ignore.
for kind, value in (("background", 0), ("paint", 1), ("unknown", 255)):
for y, a, b in checked[kind]:
if not y0 <= y < y1 or not x0 <= a < b <= x1:
raise ValueError("Reviewed spans outside ROI")
labels[y * width + a : y * width + b] = bytes([value]) * (b - a)
if sum(v != 3 for v in labels) != (x1 - x0) * (y1 - y0):
raise ValueError("Incomplete ROI; unassigned is not reviewed unknown")
typed = "source_unknown" in record
source = pixel_runs(
dict(paint=[], background=[], unknown=record.get("source_unknown", [])), size
)["unknown"]
source_mask = _mask(source, width, count)
if any(mark and labels[i] != 255 for i, mark in enumerate(source_mask)):
raise ValueError("Source unknown must be within reviewed unknown")
automatic = _difference(checked["unknown"], source_mask, width) if typed else []
untyped = [] if typed else checked["unknown"]
categories = dict(source_unknown=source, automatic_margin=automatic, untyped_unknown=untyped)
# Check the disjoint union independently with the normal RLE validator.
union = sorted(span for spans in categories.values() for span in spans)
pixel_runs(dict(paint=[], background=[], unknown=union), size)
if _mask(union, width, count) != _mask(checked["unknown"], width, count):
raise ValueError("Unknown provenance union differs")
prior = protected or bytes(count)
outside = dict(pixels=0, prior_known=0, prior_protected_untyped=0, unassigned_unknown=0)
prior_counts = dict(pixels=0, inside_roi=0, outside_roi=0, remaining_unknown=0)
for i, (old, new, value) in enumerate(zip(original, merged, labels, strict=True)):
if prior[i]:
if old != 255 or new != 255:
raise ValueError("Prior protected unknown changed")
prior_counts["pixels"] += 1
prior_counts["inside_roi" if value != 3 else "outside_roi"] += 1
prior_counts["remaining_unknown"] += 1
if source_mask[i] and (old != 255 or new != 255):
raise ValueError("Source unknown conflicts with accepted labels")
if old != 255 and new != old:
raise ValueError("Accepted known label changed")
expected = value if value in (0, 1) else old
if new != expected:
raise ValueError("Merged target differs from source-to-merge contract")
if value == 3:
outside["pixels"] += 1
key = (
"prior_known"
if old != 255
else "prior_protected_untyped"
if prior[i]
else "unassigned_unknown"
)
outside[key] += 1
proof = {}
for kind, spans in categories.items():
mask = _mask(spans, width, count)
counts = dict(
pixels=0, remaining_unknown=0, retained_old_paint=0, retained_old_background=0
)
for i, mark in enumerate(mask):
if mark:
counts["pixels"] += 1
key = {
255: "remaining_unknown",
1: "retained_old_paint",
0: "retained_old_background",
}[merged[i]]
counts[key] += 1
proof[kind] = dict(runs=spans, mask_sha256=sha(mask), **counts)
return dict(
schema="missioncore.annotation-provenance/v1",
view=record["view"],
size=list(size),
roi=list(packet["roi"]),
original_sha256=sha(original),
merged_sha256=sha(merged),
protected_sha256=sha(protected),
record_sha256=digest(record),
source_subtypes_known=typed,
categories=proof,
prior_protected_untyped=prior_counts,
outside_roi=outside,
reviewed_pixels=(x1 - x0) * (y1 - y0),
labels_changed_by_audit=0,
)
@@ -0,0 +1,44 @@
"""Apply reviewed known-to-unknown withdrawals to TRAIN-only paired targets."""
import numpy as np
def training_view(record, revised):
if record["split"] != "train":
raise ValueError("TRAIN records only")
old, base = record["target"], record["base_target"]
arrays = [old, base, revised]
if any(
a.dtype != np.uint8
or a.ndim != 2
or a.shape != old.shape
or not np.isin(a, [0, 1, 255]).all()
for a in arrays
):
raise ValueError("Aligned uint8 targets required")
if not np.array_equal(old[base != 255], base[base != 255]):
raise ValueError("Parent base labels conflict")
if not np.array_equal(old == 0, base == 0):
raise ValueError("Parent comparison admits paint only")
changed = old != revised
if np.any(changed & ((old == 255) | (revised != 255))):
raise ValueError("Known-to-unknown withdrawal only")
for name in ["weak", "clear", "added"]:
mask = record[name]
if mask.dtype != bool or mask.shape != old.shape or np.any(mask & (old != 1)):
raise ValueError("Pinned condition masks must select parent paint")
if not np.array_equal(record["added"], (base == 255) & (old == 1)):
raise ValueError("Added cohort differs from parent labels")
if np.any(changed & (record["weak"] | record["added"])):
raise ValueError("This fixed comparison preserves all weak and added paint")
target = revised.copy()
original = base.copy()
original[changed] = 255
return dict(
record,
target=target,
base_target=original,
weak=record["weak"].copy(),
added=record["added"].copy(),
clear=record["clear"] & (target == 1),
)
@@ -0,0 +1,106 @@
"""Pinned TRAIN-only background admission with fixed existing window mass."""
import hashlib
import numpy as np
from condition_inventory import raster
from PIL import Image, ImageFilter
def add_background(sample, review, target, protected):
if sample["split"] != "train" or review["name"] != sample["name"]:
raise ValueError("Pinned TRAIN sample required")
if (
target.dtype != np.uint8
or target.ndim != 2
or list(target.shape[::-1]) != sample["size"]
or not np.isin(target, [0, 1, 255]).all()
or protected.dtype != bool
or protected.shape != target.shape
or np.any(protected & (target != 255))
):
raise ValueError("Aligned labels and unknown-only protected mask required")
for key, actual in [
("target_sha256", hashlib.sha256(target.tobytes()).hexdigest()),
("protected_sha256", hashlib.sha256(protected.tobytes()).hexdigest()),
("rgb_sha256", sample["rgb_sha256"]),
]:
if review[key] != actual or sample[key] != actual:
raise ValueError("Pinned source or target changed")
if review["boundary_ignore_px"] != 2 or not isinstance(review["regions"], list):
raise ValueError("Explicit two-native-pixel uncertainty margin required")
if len(review["regions"]) > 32:
raise ValueError("Bounded reviewed regions required")
added = np.zeros(target.shape, dtype=bool)
audit, seen = [], set()
for region in review["regions"]:
if not region["reason"].strip() or not region["id"] or region["id"] in seen:
raise ValueError("Unique region identity and visible-source reason required")
seen.add(region["id"])
mask = raster(region["polygon"], sample["size"])
core = (
np.asarray(Image.fromarray(mask.astype("uint8") * 255).filter(ImageFilter.MinFilter(5)))
> 0
)
if np.any(core & (target == 1)):
raise ValueError("Reviewed background conflicts with accepted paint")
fresh = core & (target == 255) & ~protected
if np.any(fresh & added):
raise ValueError("Overlapping added-background interiors")
added |= fresh
audit.append(
dict(
id=region["id"],
new_pixels=int(fresh.sum()),
known_background=int((core & (target == 0)).sum()),
protected_excluded=int((core & protected).sum()),
)
)
out = target.copy()
out[added] = 0
return out, added, audit
def prepare_background(records, weights):
"""Keep positive weights exact; redistribute each window's existing BG mass.
New negatives may enter only windows already containing reviewed background.
Empty additions are an exact identity, including dtype and sample order.
"""
if not records or set(weights) != {r["name"] for r in records}:
raise ValueError("Matching nonempty records and weights required")
output, result, seen = [], {}, set()
for r in records:
name = r["name"]
if r["split"] != "train" or name in seen:
raise ValueError("Unique TRAIN records required")
seen.add(name)
target, added, w = r["target"], r["added_background"], weights[name]
if (
target.dtype != np.uint8
or target.ndim != 2
or not np.isin(target, [0, 1, 255]).all()
or added.dtype != bool
or added.shape != target.shape
or w.shape != target.shape
or w.dtype.kind != "f"
or not np.isfinite(w).all()
or np.any(w < 0)
or np.any(w[target == 255] != 0)
or np.any(added & (target != 255))
):
raise ValueError("Invalid labels, admitted background or weights")
t, ww = target.copy(), w.copy()
nadd = int(added.sum())
if nadd:
existing = target == 0
nold = int(existing.sum())
if not nold or np.any(w[existing] <= 0):
raise ValueError("Existing positive background mass required in each added window")
mass = float(w[existing].sum(dtype=np.float64))
ww[existing] *= nold / (nold + nadd)
ww[added] = mass / (nold + nadd)
t[added] = 0
output.append(dict(r, target=t))
result[name] = ww
return output, result
@@ -0,0 +1,87 @@
"""Worker-only rendering of the previously frozen six control windows."""
import hashlib
import json
import time
from pathlib import Path
from mapping import prepare_crops, render
from PIL import Image, ImageDraw
root = Path("/experiment")
control = json.loads((root / "control.json").read_text())
source = json.loads((root / "control-source-receipt.json").read_text())["source"]
out = root / "control-observations"
out.mkdir(exist_ok=False)
start = time.monotonic()
jobs = []
for w in control["windows"]:
x, y, z = w["center"]
views = [
dict(
id="top",
projection="ortho",
size=[768, 768],
width_m=12,
eye=[x, y, z + 25],
target=[x, y, z],
up=[0, 1, 0],
),
dict(
id="oblique",
projection="pinhole",
size=[768, 768],
fov_degrees=65,
eye=[x, y - 7, z + 9],
target=[x, y, z],
up=[0, 0, 1],
),
]
jobs.append(
dict(
source=source,
bounds_xy=[[x - 6, y - 6], [x + 6, y + 6]],
halo_m=15,
views=views,
)
)
for start_index in range(0, len(jobs), 3):
batch = jobs[start_index : start_index + 3]
for i, (job, rows) in enumerate(zip(batch, prepare_crops(batch), strict=True)):
w = control["windows"][start_index + i]
folder = out / w["id"]
folder.mkdir()
(folder / "cameras.json").write_text(json.dumps(job, allow_nan=False))
render(job, folder, prepared_rows=rows)
del rows
sheet = Image.new("RGB", (1536, 800), "#161616")
for n, view in enumerate(["top", "oblique"]):
sheet.paste(Image.open(folder / (view + ".png")), (n * 768, 32))
ImageDraw.Draw(sheet).text(
(12, 10),
w["id"] + " | RAW TOP / RAW OBLIQUE | no algorithm overlay",
fill="white",
)
sheet.save(folder / "raw-review.jpg", quality=94)
print("complete " + w["id"], flush=True)
files = {
p.relative_to(out).as_posix(): dict(
bytes=p.stat().st_size, sha256=hashlib.sha256(p.read_bytes()).hexdigest()
)
for p in out.rglob("*")
if p.is_file()
}
manifest = dict(
schema_version="missioncore.boundary-control-observations/v1",
control_sha256=hashlib.sha256((root / "control.json").read_bytes()).hexdigest(),
source=source,
files=files,
seconds=time.monotonic() - start,
training_eligible=False,
)
(out / "manifest.json").write_text(json.dumps(manifest, indent=2, allow_nan=False))
print(
json.dumps(
dict(seconds=manifest["seconds"], bytes=sum(f["bytes"] for f in files.values()))
)
)
@@ -0,0 +1,354 @@
"""Offline RGB/depth ranking probe. Never substitutes production admission.
Uses the existing four physical evidence terms, without learned masks or
occluder fields (absent from the reviewed image pack). Consequently its fixed
score is a diagnostic reference, NOT the production algorithm's full score.
"""
import argparse
import hashlib
import json
import time
from pathlib import Path
import numpy as np
from boundary_anchors import PhysicalFields, resample, sample
from boundary_review import clipped_range, verify_pack
from PIL import Image, ImageDraw
from scipy.optimize import minimize
PRIOR = np.array([0.65, 0.65, 0.25, 0.20], dtype=np.float64)
TERMS = ["persistent_contrast_edge", "height_step", "oriented_edge", "side_texture"]
def components(fields, uv, normal):
"""Same float32 arrays, interpolation and constants as PhysicalFields.measure."""
n = np.broadcast_to(normal, uv.shape)
plus = uv + n * fields.policy.cross_section_m / fields.cell
minus = uv - n * fields.policy.cross_section_m / fields.cell
near = sample(fields.gray, plus) - sample(fields.gray, minus)
far = sample(fields.gray, uv + n * 0.8 / fields.cell) - sample(
fields.gray, uv - n * 0.8 / fields.cell
)
contrast = np.clip(np.minimum(abs(near), abs(far)) / 18, 0, 1) * (near * far > 0)
edge = np.clip(
abs(sample(fields.gx, uv) * n[..., 0] + sample(fields.gy, uv) * n[..., 1]) / 55,
0,
1,
)
dz = sample(fields.z, plus) - sample(fields.z, minus)
step = np.exp(-(((dz - 0.12) / 0.12) ** 2)) * (dz > 0.025) * (dz < 0.35)
texture = np.clip(
(sample(fields.texture, plus) - sample(fields.texture, minus)) / 20, 0, 1
)
score, reliable = fields.measure(uv, normal)
# The retained fixed score comes from production code, not a reordered sum.
return np.stack([contrast * edge, step, edge, texture], axis=-1) * reliable[
..., None
], score * reliable
def fields_for(folder):
rgb = np.array(Image.open(folder / "top.png").convert("RGB"))
g = np.load(folder / "top.geometry.npz")
z = g["view"][2, 3] - g["depth"]
zero = np.zeros(z.shape, np.float32)
cell = 1 / float(g["intrinsics"][0, 0])
return PhysicalFields(rgb, z, g["alpha"], zero, zero, zero, cell), g
def project(points, g):
xyz = np.asarray(points, dtype=np.float64)
view, k = g["view"], g["intrinsics"]
camera = xyz @ view[:3, :3].T + view[:3, 3]
return camera[:, :2] * np.diag(k)[:2] + k[:2, 2] - 0.5
def describe(fields, path, rect, sidewalk_direction):
chunks = []
lengths = []
baseline = []
sidewalk = np.asarray(sidewalk_direction, dtype=float)
if (
sidewalk.shape != (2,)
or not np.isfinite(sidewalk).all()
or np.linalg.norm(sidewalk) == 0
):
raise ValueError("Explicit review orientation required")
for a, b in zip(path, path[1:], strict=False):
clip = clipped_range(a, b, rect)
if clip is None:
continue
a, b = np.asarray(a), np.asarray(b)
ends = np.array([a + t * (b - a) for t in clip])
length = float(np.linalg.norm(ends[1] - ends[0]) * fields.cell)
if length < 1e-8:
continue
# Measurements only: never store these samples as replacement geometry.
points = resample(ends * fields.cell, 0.20) / fields.cell
tangent = (b - a) / np.linalg.norm(b - a)
n = np.array([-tangent[1], tangent[0]])
if n @ sidewalk < 0:
n = -n
feature, score = components(fields, points, n)
chunks.append(feature.mean(0))
baseline.append(float(score.mean()))
lengths.append(length)
if not chunks:
raise ValueError("Candidate has no reviewed extent")
return np.average(chunks, axis=0, weights=lengths), float(
np.average(baseline, weights=lengths)
)
def fit(differences, prior=PRIOR):
d = np.asarray(differences, dtype=np.float64)
if d.ndim != 2 or d.shape[1] != 4 or len(d) < 2 or not np.isfinite(d).all():
raise ValueError("Finite, reviewed candidate pairs required")
# Fixed before held-out evaluation. No hyperparameter search on control.
def objective(w):
return np.logaddexp(0, -d @ w).mean() + 0.1 * np.square(w - prior).sum()
result = minimize(
objective,
prior,
method="L-BFGS-B",
bounds=[(0, 2)] * 4,
options={"maxiter": 100, "ftol": 1e-12, "gtol": 1e-8},
)
if not result.success or not np.isfinite(result.x).all():
raise ValueError("Ranking fit did not converge")
return result.x
def train(root, pack_name="expanded-pack", run_name="rank-probe"):
start = time.monotonic()
pack = root / pack_name
verification = verify_pack(pack)
review = json.loads((root / "control-review.json").read_text())
control = json.loads((root / "control.json").read_text())
train_world = json.loads((pack / "pack.json").read_text())["source"]["world_sha256"]
if (
review["training_eligible"] is not False
or not review["reviewed_before_fit"]
or review["control_sha256"]
!= hashlib.sha256((root / "control.json").read_bytes()).hexdigest()
or control["world_sha256"] == train_world
):
raise ValueError("Frozen independent visual control required before fit")
records = json.loads((pack / "records.json").read_text())
orientation = json.loads((root / "training-orientation.json").read_text())
rows = []
for r in records:
if not r["ranking_trial_eligible"]:
continue
folder = pack / "observations" / Path(r["sample"]).parent
labels = json.loads((folder / "labels.json").read_text())
fields, g = fields_for(folder)
def candidate(key, labels=labels, r=r, fields=fields, g=g):
f = next(f for f in labels[key] if f["id"] == r["feature_id"])
return describe(
fields,
project(f["geometry"]["coordinates"], g),
r["rect_px"],
orientation[r["id"]],
)
positive, pb = candidate("proposed_element")
negative, nb = candidate("original_element")
rows.append(
dict(
id=r["id"],
feature_id=r["feature_id"],
sample=r["sample"],
positive=positive.tolist(),
negative=negative.tolist(),
fixed_margin=pb - nb,
)
)
preparation = time.monotonic() - start
d = np.array([np.array(r["positive"]) - r["negative"] for r in rows])
training = time.monotonic()
w = fit(d)
training = time.monotonic() - training
# Leave entire source feature out, including distant windows on that feature.
loo = []
for fid in sorted({r["feature_id"] for r in rows}):
hold = np.array([r["feature_id"] == fid for r in rows])
lw = fit(d[~hold])
loo.extend(
dict(id=rows[i]["id"], margin=float(d[i] @ lw))
for i in np.flatnonzero(hold)
)
for r, margin in zip(rows, d @ w, strict=True):
r["learned_margin"] = float(margin)
model = dict(
schema_version="missioncore.boundary-rank-probe/v1",
terms=TERMS,
weights=w.tolist(),
prior=PRIOR.tolist(),
training_pack_sha256=verification["sha256"],
training_world_sha256=json.loads((pack / "pack.json").read_text())["source"][
"world_sha256"
],
control_sha256=hashlib.sha256((root / "control.json").read_bytes()).hexdigest(),
acceptance_changed=False,
production_eligible=False,
missing_production_fields=["semantic_context", "occluder"],
l2_to_prior=0.1,
weight_bounds=[0, 2],
sample_m=0.2,
review_orientation=True,
source_sha256=hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
physical_fields_sha256=hashlib.sha256(
(root / "boundary_anchors.py").read_bytes()
).hexdigest(),
)
model["control_review_sha256"] = hashlib.sha256(
(root / "control-review.json").read_bytes()
).hexdigest()
target = root / run_name
target.mkdir(exist_ok=False)
(target / "model.json").write_text(json.dumps(model, indent=2, allow_nan=False))
report = dict(
rows=rows,
leave_feature_out=loo,
preparation_seconds=preparation,
training_seconds=training,
pairs=len(rows),
independent_source_features=len(set(r["feature_id"] for r in rows)),
fixed_correct=sum(r["fixed_margin"] > 0 for r in rows),
fit_correct=sum(r["learned_margin"] > 0 for r in rows),
leave_feature_out_correct=sum(r["margin"] > 0 for r in loo),
full_chain_run=False,
)
(target / "training-report.json").write_text(
json.dumps(report, indent=2, allow_nan=False)
)
print(json.dumps(report, allow_nan=False))
def evaluate(root, run_name="rank-probe"):
start = time.monotonic()
target = root / run_name
model = json.loads((target / "model.json").read_text())
review = json.loads((root / "control-review.json").read_text())
if (
model["control_review_sha256"]
!= hashlib.sha256((root / "control-review.json").read_bytes()).hexdigest()
):
raise ValueError("Control review changed after fitting")
if (
model["source_sha256"]
!= hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
):
raise ValueError("Probe implementation changed after fitting")
observations = root / "control-observations"
if (
review["observations_sha256"]
!= hashlib.sha256((observations / "manifest.json").read_bytes()).hexdigest()
):
raise ValueError("Control observation identity changed")
manifest = json.loads((observations / "manifest.json").read_text())
for name, spec in manifest["files"].items():
p = (observations / name).resolve()
if (
not p.is_relative_to(observations.resolve())
or hashlib.sha256(p.read_bytes()).hexdigest() != spec["sha256"]
):
raise ValueError("Control observation member changed")
rows = []
for r in review["records"]:
if not r["eligible"]:
rows.append(dict(id=r["id"], status="unscored-unknown", reason=r["reason"]))
continue
folder = observations / r["id"]
fields, g = fields_for(folder)
path = np.array(r["path_px"], dtype=float)
direction = np.array(r["sidewalk_direction"], dtype=float)
direction /= np.linalg.norm(direction)
choices = []
for offset in review["candidate_offsets_m"]:
candidate = path + offset / fields.cell * direction
feature, fixed = describe(fields, candidate, r["rect_px"], direction)
choices.append(
dict(
offset_m=offset,
fixed_score=fixed,
learned_score=float(feature @ model["weights"]),
)
)
fixed = max(choices, key=lambda x: x["fixed_score"])
learned = max(choices, key=lambda x: x["learned_score"])
row = dict(
id=r["id"],
status="diagnostic-only",
fixed_offset_m=fixed["offset_m"],
learned_offset_m=learned["offset_m"],
fixed_abs_offset_m=abs(fixed["offset_m"]),
learned_abs_offset_m=abs(learned["offset_m"]),
choices=choices,
)
rows.append(row)
raw = Image.open(folder / "top.png").convert("RGB")
over = raw.copy()
draw = ImageDraw.Draw(over)
for offset, color in [
(fixed["offset_m"], "#ff9750"),
(learned["offset_m"], "#c77dff"),
(0, "#55ff8b"),
]:
p = path + offset / fields.cell * direction
draw.line([tuple(x) for x in p], fill=color, width=3)
sheet = Image.new("RGB", (1536, 800), "#161616")
sheet.paste(raw, (0, 32))
sheet.paste(over, (768, 32))
ImageDraw.Draw(sheet).text(
(12, 10),
r["id"]
+ " | raw / green: visual reference; orange: fixed physical score; purple: learned",
fill="white",
)
sheet.save(target / (r["id"] + "-evaluation.jpg"), quality=94)
report = dict(
rows=rows,
seconds=time.monotonic() - start,
model_sha256=hashlib.sha256((target / "model.json").read_bytes()).hexdigest(),
scored_windows=sum(r["eligible"] for r in review["records"]),
unknown_windows=sum(not r["eligible"] for r in review["records"]),
full_chain_run=False,
production_eligible=False,
acceptance_changed=False,
limitation=("Two locally visible control segments. RGB/depth feature probe lacks "
"production semantic context and occluder fields; approximate visual "
"references. No deployment or general accuracy claim."),
)
p = target / "evaluation.json"
if p.exists():
raise ValueError("Do not overwrite frozen evaluation")
p.write_text(json.dumps(report, indent=2, allow_nan=False))
print(
json.dumps(
{
**report,
"rows": [{k: v for k, v in r.items() if k != "choices"} for r in rows],
}
)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["train", "evaluate"])
parser.add_argument("--root", type=Path, default=Path("/experiment"))
parser.add_argument("--pack", default="expanded-pack")
parser.add_argument("--run", default="rank-probe")
args = parser.parse_args()
if any(Path(s).name != s or s in {".", ".."} for s in (args.pack, args.run)):
parser.error("Pack/run must be direct child directory names")
if args.action == "evaluate":
evaluate(args.root, args.run)
else:
train(args.root, args.pack, args.run)
@@ -0,0 +1,238 @@
"""Portable, explicitly reviewed boundary evidence; no implicit pixel/background truth.
Run on Worker. A reviewer selects a rectangle in an existing orthographic image.
The target is a range on the original stored polyline, never a refitted curve.
Only an explicit relative preference is eligible for the first ranking trial.
"""
import argparse
import math
import shutil
from pathlib import Path
from dataset_store import checksum, confined, digest, read, review_samples, write
SCHEMA = "missioncore.boundary-review-pack/v1"
LIMIT = 96 * 1024**2
def clipped_range(a, b, rect):
"""Liang–Barsky parameters on the unchanged source segment (pixel centres)."""
lo, hi = 0.0, 1.0
for axis in (0, 1):
delta = b[axis] - a[axis]
if delta == 0:
if not rect[axis] <= a[axis] <= rect[axis + 2]:
return None
else:
x, y = sorted(((rect[axis] - a[axis]) / delta, (rect[axis + 2] - a[axis]) / delta))
lo, hi = max(lo, x), min(hi, y)
return [lo, hi] if hi > lo else None
def compile_record(labels, cameras, decision):
if decision["evidence"] not in {"visible", "context", "uncertain"}:
raise ValueError("Unknown evidence category")
if not decision.get("reviewer") or not decision.get("reason"):
raise ValueError("Explicit reviewer and reason required")
feature = next(f for f in labels["proposed_element"] if f["id"] == decision["feature_id"])
if (
feature["properties"]["class"] != "road_boundary"
or feature["properties"].get("review_status") == "rejected"
or feature["geometry"]["type"] != "LineString"
):
raise ValueError("Expected an active road boundary LineString")
camera = next(c for c in cameras["views"] if c["id"] == decision["view"])
if camera["projection"] != "ortho":
raise ValueError("Review ranges currently require orthographic projection")
rect = decision["rect_px"]
if (
len(rect) != 4
or not all(math.isfinite(x) for x in rect)
or not 0 <= rect[0] < rect[2] < camera["size"][0]
or not 0 <= rect[1] < rect[3] < camera["size"][1]
):
raise ValueError("Review rectangle outside image")
projections = [
p for p in labels["projections"][decision["view"]] if p["feature_id"] == feature["id"]
]
if len(projections) != 1:
raise ValueError("Ambiguous source path")
projection = projections[0]
points = feature["geometry"]["coordinates"]
uv = projection["uv"]
if len(points) != len(uv) or len(points) != len(projection["in_front"]):
raise ValueError("Projection/path identity mismatch")
ranges = []
for i, (a, b) in enumerate(zip(uv, uv[1:], strict=False)):
if not all(math.isfinite(v) for v in (*a, *b, *points[i], *points[i + 1])):
raise ValueError("Non-finite observation")
span = clipped_range(a, b, rect)
if span and projection["in_front"][i] and projection["in_front"][i + 1]:
ranges.append(dict(segment=i, t=span))
if not ranges:
raise ValueError("Review rectangle contains no source segment")
original = next((f for f in labels["original_element"] if f["id"] == feature["id"]), None)
preference = decision.get("preference")
if preference not in {None, "edited-better-than-original"}:
raise ValueError("Unknown ranking preference")
eligible = preference is not None and decision["evidence"] == "visible"
if preference and (
not eligible or original is None or original["geometry"] == feature["geometry"]
):
raise ValueError("Preference requires visible evidence and distinct source candidates")
return dict(
**decision,
geometry_sha256=digest(feature["geometry"]),
original_geometry_sha256=digest(original["geometry"]) if original else None,
camera_sha256=digest(camera),
path=0,
segment_ranges=ranges,
ranking_trial_eligible=eligible,
metric_ground_truth=False,
dense_segmentation_eligible=False,
background_targets=[],
complete_regions=[],
human_approved=False,
)
def check_control(control, train_world):
if (
control.get("schema_version") != "missioncore.boundary-control/v1"
or control.get("role") != "held-out-scene"
or control.get("world_sha256") == train_world
or control.get("training_eligible") is not False
or not control.get("windows")
or not control.get("frozen_utc")
):
raise ValueError("A distinct frozen control scene is required")
for key in ("world_sha256", "model_sha256"):
value = control.get(key, "")
if len(value) != 64 or any(c not in "0123456789abcdef" for c in value):
raise ValueError("Control source identity required")
def verify_pack(root):
root = Path(root)
manifest = read(root / "pack.json")
if manifest["schema_version"] != SCHEMA:
raise ValueError("Unsupported boundary pack")
actual = {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()}
if actual != set(manifest["files"]) | {"pack.json"}:
raise ValueError("Unexpected pack member")
total = 0
for name, spec in manifest["files"].items():
path = confined(root, name)
total += path.stat().st_size
if path.stat().st_size != spec["bytes"] or checksum(path) != spec["sha256"]:
raise ValueError("Pack member changed: " + name)
if total > LIMIT:
raise ValueError("Boundary pack exceeds bounded size")
decisions = read(root / "decisions.json")
check_control(read(root / "control.json"), manifest["source"]["world_sha256"])
records = []
for decision in decisions["records"]:
folder = Path("observations") / Path(decision["sample"]).parent
labels = read(confined(root, (folder / "labels.json").as_posix()))
cameras = read(confined(root, (folder / "cameras.json").as_posix()))
records.append(compile_record(labels, cameras, decision))
if records != read(root / "records.json"):
raise ValueError("Admission differs from reviewed evidence")
return dict(
sha256=checksum(root / "pack.json"),
bytes=total,
records=len(records),
ranking_pairs=sum(r["ranking_trial_eligible"] for r in records),
)
def build_pack(source, decisions, control, destination):
source, destination = Path(source), Path(destination)
if destination.exists() or destination.resolve().is_relative_to(source.resolve()):
raise ValueError("Use a new destination outside the immutable source dataset")
if checksum(source / "dataset.json") != decisions["dataset_sha256"]:
raise ValueError("Reviewed collection changed")
if not 1 <= len(decisions["records"]) <= 12:
raise ValueError("First review pack is bounded to twelve decisions")
if len({r["id"] for r in decisions["records"]}) != len(decisions["records"]):
raise ValueError("Duplicate review identity")
wanted = {d["sample"] for d in decisions["records"]}
# This verifies the complete immutable collection before selecting a small subset.
rows = {row["sample"]: row for row in review_samples(source) if row["sample"] in wanted}
if set(rows) != wanted:
raise ValueError("Unknown reviewed sample")
identity = next(iter(rows.values()))["source"]
if any(r["source"] != identity for r in rows.values()):
raise ValueError("Mixed source revisions")
check_control(control, identity["world_sha256"])
files = {"provenance/collection.json": source / "dataset.json"}
records = []
for d in decisions["records"]:
sample = confined(source, d["sample"])
folder = sample.parent
labels, cameras = read(folder / "labels.json"), read(folder / "cameras.json")
records.append(compile_record(labels, cameras, d))
shard = read(folder.parent / "dataset.json")
part = folder.parent.name
files[f"provenance/{part}.json"] = folder.parent / "dataset.json"
files["provenance/annotation.json"] = folder.parent / "annotation.json"
for name in read(sample)["members"] + [folder.name + "/sample.json"]:
member = confined(folder.parent, name)
if name not in shard["files"]:
raise ValueError("Unbound observation")
files[f"observations/{part}/{name}"] = member
if sum(p.stat().st_size for p in files.values()) > LIMIT - 1024**2:
raise ValueError("Selected observations exceed size budget")
destination.parent.mkdir(parents=True, exist_ok=True)
if shutil.disk_usage(destination.parent).free < 12 * 1024**3 + LIMIT:
raise ValueError("Worker disk reserve would be exceeded")
staging = destination.with_name(destination.name + ".partial")
staging.mkdir() # No overwrite of another attempt.
for name, origin in files.items():
target = staging / name
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(origin, target)
if checksum(target) != checksum(origin):
raise ValueError("Observation copy changed")
for name, value in (
("decisions.json", decisions),
("control.json", control),
("records.json", records),
):
write(staging / name, value)
# A standalone stdlib reader travels with the pack.
for script in (Path(__file__), Path(__file__).with_name("dataset_store.py")):
shutil.copyfile(script, staging / script.name)
write(
staging / "pack.json",
dict(
schema_version=SCHEMA,
source=identity,
source_collection_sha256=decisions["dataset_sha256"],
usage="local-boundary-ranking-trial",
dense_segmentation_eligible=False,
files={
p.relative_to(staging).as_posix(): dict(sha256=checksum(p), bytes=p.stat().st_size)
for p in sorted(staging.rglob("*"))
if p.is_file()
},
),
)
result = verify_pack(staging)
staging.rename(destination)
return result
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("root", type=Path)
parser.add_argument("--decisions", type=Path)
parser.add_argument("--control", type=Path)
parser.add_argument("--output", type=Path)
args = parser.parse_args()
if args.output:
result = build_pack(args.root, read(args.decisions), read(args.control), args.output)
else:
result = verify_pack(args.root)
print(result)
@@ -0,0 +1,347 @@
"""GPU sample builder. Executed only inside the Worker renderer container."""
import time
from pathlib import Path
import numpy as np
from dataset_store import SCHEMA, checksum, read, write
from mapping import camera, prepare_crops, render
from PIL import Image
def contexts(package):
import copy
import math
from semantic_objects import members, object_operation, pivot
from semantic_vectors import knots, vector_operation
features = copy.deepcopy(package["model"]["features"])
def replay(op, origin="human-edit"):
nonlocal features
f = next((f for f in features if f["id"] == op.get("feature_id")), None)
curved = f and f["properties"].get("editor_curves", {}).get(str(op.get("path")))
if op["kind"] in ("place", "transform", "remove", "retemplate"):
features = object_operation(features, op, origin=origin)
elif (
op["kind"]
in (
"curve",
"delete_vertices",
"region",
"translate",
"translate_vertices",
"duplicate_vertex",
"duplicate_marking",
)
or curved
):
features = vector_operation(features, op, origin=origin)
else:
apply(f, op)
for row in package["revisions"][:-1]:
for op in row["operations"]:
replay(op, row.get("origin", "human-edit"))
before = copy.deepcopy(features)
affected = []
for op in package["revisions"][-1]["operations"]:
kind = op["kind"]
fid = op.get("feature_id")
anchors = []
if kind in ("delete_vertices", "translate", "translate_vertices") and op["vertices"]:
for v in op["vertices"]:
f = next(f for f in features if f["id"] == v["feature_id"])
anchors.append((f["id"], knots(f, v["path"])[v["index"]]["point"]))
elif kind == "region":
for a, b in zip(op["brush"], op["brush"][1:], strict=False):
count = max(1, math.ceil(math.dist(a[:2], b[:2]) / 6))
if count > 32:
raise ValueError("Region exceeds bounded observation windows")
anchors.extend(
(fid, [a[k] + j / count * (b[k] - a[k]) for k in range(3)])
for j in range(count)
)
elif kind == "place":
anchors = [(fid, op["position"])]
elif kind in ("transform", "remove", "translate", "duplicate_marking", "retemplate"):
anchors = [(fid, pivot(members(features, fid)))]
else:
f = next(f for f in features if f["id"] == fid)
anchors = [(fid, knots(f, op["path"])[op["index"]]["point"])]
replay(op, package["revisions"][-1].get("origin", "human-edit"))
for fid, old in anchors:
point = (
[v + op["delta"][k] for k, v in enumerate(old)]
if kind
in ("translate", "translate_vertices", "duplicate_vertex", "duplicate_marking")
else op.get("position", old)
)
if kind == "transform":
point = pivot(members(features, fid))
if math.dist(point, old) > 8:
raise ValueError("Edit displacement exceeds bounded observation window")
centre = [(a + b) / 2 for a, b in zip(old, point, strict=True)]
if kind == "duplicate_marking":
fid = op["new_feature_id"]
selected = next(f for f in features if f["id"] == fid)
group = selected["properties"].get("semantic_element_id", fid)
if not any(
previous == group and math.dist(c[:2], centre[:2]) < 3 for previous, c in affected
):
affected.append((group, centre))
if not 1 <= len(affected) <= 16:
raise ValueError("Split edits into at most 16 local observation windows")
return before, features, affected
def centres(package):
return contexts(package)[2]
def apply(feature, op):
g = feature["geometry"]
points = g["coordinates"][op["path"]] if g["type"] == "Polygon" else g["coordinates"]
i = op["index"]
if op["kind"] == "move":
points[i] = op["position"][:]
elif op["kind"] == "insert":
a, b = points[i : i + 2]
points.insert(i + 1, [a[k] + op["t"] * (b[k] - a[k]) for k in range(3)])
else:
points.pop(i)
if g["type"] == "Polygon":
points[-1] = points[0][:]
def build():
start = time.monotonic()
batch = read("/job/batch.json") if Path("/job/batch.json").exists() else None
out = Path("/output") / batch["name"] if batch else Path("/output")
out.mkdir(exist_ok=True)
envelope = read("/job/envelope.json")
source = read("/job/source.json")
package = envelope["annotation"]["package"]
from semantic_objects import members
if batch:
from final_snapshot import plan
snapshot = plan(package, batch["classes"])
if snapshot != read("/job/plan.json"):
raise ValueError("Snapshot plan changed")
windows = snapshot["windows"][batch["start"] : batch["stop"]]
if not 1 <= len(windows) <= 4:
raise ValueError("Invalid bounded shard")
previous = package["model"]["features"]
replayed = package["edited"]["features"]
affected = [(w["features"][0], w["center"]) for w in windows]
else:
previous, replayed, affected = contexts(package)
proposed = package["edited"]["features"]
if {f["id"]: f["geometry"] for f in replayed} != {f["id"]: f["geometry"] for f in proposed}:
raise ValueError("Replayed geometry differs from the admitted edit")
after = {f["id"]: f for f in proposed}
before = {f["id"]: f for f in previous}
samples = []
crop_jobs = [
dict(
source=source, bounds_xy=[[xyz[0] - 6, xyz[1] - 6], [xyz[0] + 6, xyz[1] + 6]], halo_m=15
)
for _, xyz in affected
]
crops = prepare_crops(crop_jobs) if batch else None
for i, (fid, xyz) in enumerate(affected):
name = windows[i]["id"] if batch else f"sample-{i:03d}"
folder = out / name
folder.mkdir(exist_ok=True)
x, y, z = xyz
specs = [
dict(
id="top",
projection="ortho",
size=[768, 768],
width_m=12,
eye=[x, y, z + 25],
target=[x, y, z],
up=[0, 1, 0],
),
dict(
id="oblique",
projection="pinhole",
size=[768, 768],
fov_degrees=65,
eye=[x, y - 7, z + 9],
target=[x, y, z],
up=[0, 0, 1],
),
]
job = dict(
source=source, bounds_xy=[[x - 6, y - 6], [x + 6, y + 6]], halo_m=15, views=specs
)
write(
folder / "cameras.json",
dict(
**job,
coordinates="scene-local XYZ, metres, Z up",
pixel_convention="OpenCV: pixel centres (column + 0.5, row + 0.5)",
depth_semantics="Gaussian expected centre depth; approximate, not LiDAR terrain",
height_source=(
"existing Z retained; new placements use unverified Gaussian visual pick"
),
),
)
if crops is None:
render(job, folder)
else:
crop = next(crops)
render(job, folder, prepared_rows=crop)
del crop
selected_ids = set(windows[i]["features"]) if batch else None
projections = {}
for spec in specs:
view, k = camera(spec)
g = np.load(folder / (spec["id"] + ".geometry.npz"))
observed = np.isfinite(g["depth"]) & (g["depth"] > 0) & (g["alpha"] >= 0.95)
Image.fromarray(observed.astype(np.uint8) * 255).save(
folder / (spec["id"] + ".observed.png")
)
# Unknown/unreviewed is ignored, never rasterized as background.
Image.fromarray(np.zeros((768, 768), np.uint8)).save(
folder / (spec["id"] + ".supervision.png")
)
group = after.get(fid, before.get(fid))["properties"].get("semantic_element_id")
elements = [
f
for f in proposed
if (selected_ids is not None and f["id"] in selected_ids)
or f["id"] == fid
or (group and f["properties"].get("semantic_element_id") == group)
or f["properties"].get("region_origin_id") == fid
]
paths = []
path_features = []
for element in elements:
geometry = element["geometry"]
rings = (
geometry["coordinates"]
if geometry["type"] == "Polygon"
else [geometry["coordinates"]]
)
paths.extend(rings)
path_features.extend([element["id"]] * len(rings))
pixels = []
for path, path_feature in zip(paths, path_features, strict=True):
local = np.asarray(path, dtype=np.float64) @ view[:3, :3].T + view[:3, 3]
uv = local[:, :2].copy()
if spec["projection"] == "pinhole":
uv /= np.maximum(local[:, 2, None], 1e-12)
uv = uv * np.diag(k)[:2] + k[:2, 2] - 0.5
pixels.append(
{
"feature_id": path_feature,
"uv": uv.tolist(),
"in_front": (local[:, 2] > 0).tolist(),
"inside": ((uv >= 0) & (uv < 768)).all(axis=1).tolist(),
}
)
projections[spec["id"]] = pixels
write(
folder / "labels.json",
dict(
original=before.get(fid),
original_element=[f for f in previous if f["id"] in selected_ids]
if batch
else members(previous, fid)
if fid in before
else [],
proposed_element=[f for f in proposed if f["id"] in selected_ids]
if batch
else [
f
for f in proposed
if f["id"] == fid
or f["properties"].get("semantic_element_id")
== after[fid]["properties"].get("semantic_element_id", fid)
or f["properties"].get("region_origin_id") == fid
],
proposed=after.get(fid),
projections=projections,
label_scope="final class geometry; no complete region or negative labels"
if batch
else "selected object only; no complete region or negative labels",
classes=batch["classes"] if batch else None,
window=windows[i] if batch else None,
origin=package["revisions"][-1].get("origin", "human-edit"),
review="unreviewed",
operations=package["revisions"][-1]["operations"],
),
)
member_files = [
p.relative_to(out).as_posix() for p in sorted(folder.iterdir()) if p.is_file()
]
write(
folder / "sample.json",
dict(
feature_id=fid,
members=member_files,
training_eligible=False,
complete_regions=[],
split_group=package["world_sha256"],
revision=package["revision"],
),
)
samples.append(name + "/sample.json")
write(out / "annotation.json", envelope["annotation"])
(out / "dataset_reader.py").write_bytes(
Path(__file__).with_name("dataset_store.py").read_bytes()
)
(out / "DATASET.md").write_text(
"""# Mission Core semantic correction observations
Portable review dataset, not approved training ground truth. RGB is rendered
from the pinned Gaussian source without annotation overlays. Vectors retain
original coordinates/height; cameras and pixel projections are explicit.
Use dataset_reader.review_samples(root) for review: active_candidates and
rejected_history are separate; approved_targets and background_targets remain
empty. proposed_element retains history and must never be used as a positive
label list. Even editor review_status=accepted is not per-view training approval.
The algorithm baseline and proposed edits remain separate. No unreviewed
object/region is negative background. Supervision masks are all zero (ignore).
Observed masks describe opaque Gaussian pixels, not semantic label validity.
Human approval and geometric surface-support review are still required before
supervised training. Adjacent views/revisions of one world share split_group.
No paths or URLs to Core are needed to read these samples. This does not bundle
the multi-GB source scene or claim survey-grade depth or a trained model.
""",
encoding="utf-8",
)
files = {
p.relative_to(out).as_posix(): dict(sha256=checksum(p), bytes=p.stat().st_size)
for p in sorted(out.rglob("*"))
if p.is_file() and p.name != "dataset.json"
}
write(
out / "dataset.json",
dict(
schema_version=SCHEMA,
files=files,
samples=samples,
training_eligible=False,
review="unreviewed",
source=source,
world_sha256=package["world_sha256"],
model_sha256=package["model_sha256"],
annotation_sha256=envelope["annotation"]["sha256"],
revision=package["revision"],
renderer_image=envelope["renderer_image"],
builder_sha256=checksum(__file__),
split_group=package["world_sha256"],
seconds=time.monotonic() - start,
),
)
if __name__ == "__main__":
build()
@@ -0,0 +1,334 @@
"""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]))
@@ -0,0 +1,172 @@
"""TRAIN-only visual condition sidecars over immutable observed-paint targets.
Tags describe raw evidence quality, not annotation age or an inference rule.
Region masks only select already reviewed class-compatible pixels. Unreviewed
candidate windows remain unsupervised; no target is inferred from a tag.
"""
import hashlib
import math
import numpy as np
from PIL import Image, ImageDraw
SCHEMA = "missioncore.semantic-condition-review/v1"
TAGS = {
"paint_clear": 1,
"paint_weak_visible": 1,
"background_asphalt": 0,
"background_paving": 0,
"background_utility_cover": 0,
"background_curb": 0,
}
FAMILIES = {"line", "crossing", "symbol", "hatching", "surface"}
def raster(polygon, size):
"""Convex review polygon in the explicit 512-square review coordinate frame."""
if not isinstance(polygon, list) or not 3 <= len(polygon) <= 32:
raise ValueError("Bounded convex polygon required")
if any(
not isinstance(p, list)
or len(p) != 2
or any(type(v) not in (int, float) or not math.isfinite(v) or not 0 <= v <= 512 for v in p)
for p in polygon
):
raise ValueError("Invalid review coordinates")
# Convex, consistently wound polygons have no ambiguous self-intersections.
signs = []
for i, a in enumerate(polygon):
b, c = polygon[(i + 1) % len(polygon)], polygon[(i + 2) % len(polygon)]
cross = (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
if cross:
signs.append(cross > 0)
area = sum(
a[0] * b[1] - b[0] * a[1] for a, b in zip(polygon, polygon[1:] + polygon[:1], strict=True)
)
if (
not signs
or len(set(signs)) != 1
or not area
or len(set(map(tuple, polygon))) != len(polygon)
):
raise ValueError("Degenerate or nonconvex review polygon")
# Also require every vertex to be on the same side of every edge: rejects stars.
for a, b in zip(polygon, polygon[1:] + polygon[:1], strict=True):
side = [(b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) for c in polygon]
if min(side) < 0 < max(side):
raise ValueError("Self-intersecting review polygon")
out = Image.new("1", tuple(size))
points = [(math.floor(x * size[0] / 512), math.floor(y * size[1] / 512)) for x, y in polygon]
ImageDraw.Draw(out).polygon(points, fill=1)
return np.asarray(out, dtype=bool)
def compile_record(sample, review, target):
if sample["split"] != "train" or review["name"] != sample["name"]:
raise ValueError("Conditions may only annotate the pinned TRAIN sample")
if target.dtype != np.uint8 or target.ndim != 2 or target.size > 4 * 1024**2:
raise ValueError("Bounded uint8 target required")
if list(target.shape[::-1]) != sample["size"] or not np.isin(target, [0, 1, 255]).all():
raise ValueError("Invalid target shape/classes")
expected = sample.get("target_sha256")
if sample["kind"] not in {"existing", "candidate"}:
raise ValueError("Unsupported sample kind")
if sample["kind"] == "existing" and (
not isinstance(expected, str)
or len(expected) != 64
or any(c not in "0123456789abcdef" for c in expected)
):
raise ValueError("Existing targets require an explicit SHA-256 pin")
actual = hashlib.sha256(target.tobytes()).hexdigest()
if expected is not None and actual != expected:
raise ValueError("Pinned target changed")
if sample["kind"] == "candidate" and (expected is not None or np.any(target != 255)):
raise ValueError("Unadmitted candidates cannot acquire targets from conditions")
if review["target_sha256"] != expected or review["input_sha256"] != sample["rgb_sha256"]:
raise ValueError("Review input/target identity mismatch")
regions = review["regions"]
if not isinstance(regions, list) or len(regions) > 64:
raise ValueError("Region budget exceeded")
occupied = np.zeros(target.shape, dtype=bool)
counts, masks, ids = [], {}, set()
for r in regions:
if not isinstance(r["id"], str) or not r["id"] or r["id"] in ids:
raise ValueError("Unique region identities required")
ids.add(r["id"])
if r["tag"] not in TAGS or r["family"] not in FAMILIES or not r.get("reason", "").strip():
raise ValueError("Explicit supported condition and review reason required")
if (r["family"] == "surface") != (TAGS[r["tag"]] == 0):
raise ValueError("Condition class/family mismatch")
roi = raster(r["polygon"], sample["size"])
mask = roi & (target == TAGS[r["tag"]])
if np.any(mask & occupied):
raise ValueError("Overlapping reviewed condition pixels")
occupied |= mask
masks[r["id"]] = mask
counts.append(
dict(
id=r["id"],
tag=r["tag"],
family=r["family"],
reviewed_pixels=int(mask.sum()),
region_pixels=int(roi.sum()),
unknown_region_pixels=int((roi & (target == 255)).sum()),
)
)
return dict(
name=sample["name"],
group=sample["group"],
kind=sample["kind"],
regions=counts,
untagged_paint=int(((target == 1) & ~occupied).sum()),
untagged_background=int(((target == 0) & ~occupied).sum()),
target_sha256=actual,
targets_changed=False,
), masks
def footprint(camera):
"""Axis-aligned top-view footprint in its source-local physical coordinate frame."""
if camera["projection"] != "ortho":
raise ValueError("Orthographic footprint required")
w, h = camera["size"]
if "view_matrix" not in camera:
eye, target = camera["eye"], camera["target"]
if eye[:2] != target[:2] or camera["up"] != [0, 1, 0] or eye[2] <= target[2]:
raise ValueError("Unsupported top camera")
half = camera["width_m"] / 2
return [
target[0] - half,
target[1] - half * h / w,
target[0] + half,
target[1] + half * h / w,
]
v, k = np.asarray(camera["view_matrix"], float), np.asarray(camera["intrinsics"], float)
if (
v.shape != (4, 4)
or k.shape != (3, 3)
or not np.isfinite(v).all()
or not np.isfinite(k).all()
):
raise ValueError("Invalid camera matrices")
if not np.allclose(v[:2, 2], 0) or not np.allclose([v[0, 1], v[1, 0], k[0, 1], k[1, 0]], 0):
raise ValueError("Only axis-aligned top cameras supported")
if min(k[0, 0], k[1, 1]) <= 0 or min(abs(v[0, 0]), abs(v[1, 1])) == 0:
raise ValueError("Degenerate camera")
xy = [
np.linalg.solve(v[:2, :2], (np.array([u, t]) - k[:2, 2]) / np.diag(k)[:2] - v[:2, 3])
for u, t in [(0, 0), (w, h)]
]
return [float(min(a)) for a in zip(*xy, strict=True)] + [
float(max(a)) for a in zip(*xy, strict=True)
]
def overlap_fraction(a, b):
intersection = max(0, min(a[2], b[2]) - max(a[0], b[0])) * max(
0, min(a[3], b[3]) - max(a[1], b[1])
)
if intersection < 1e-8:
return 0.0
return intersection / min((a[2] - a[0]) * (a[3] - a[1]), (b[2] - b[0]) * (b[3] - b[1]))
@@ -0,0 +1,71 @@
"""Admit reviewed context negatives while preserving per-street class mass."""
import numpy as np
def prepare_context(records, weights, additions):
names = [r["name"] for r in records]
if (
not names
or len(set(names)) != len(names)
or set(names) != set(weights)
or set(names) != set(additions)
):
raise ValueError("Matching unique TRAIN records, weights and additions required")
out, result = [], {}
for r in records:
name = r["name"]
t, w, a = r["target"], weights[name], additions[name]
if (
r["split"] != "train"
or t.dtype != np.uint8
or t.ndim != 2
or not np.isin(t, [0, 1, 255]).all()
or w.shape != t.shape
or w.dtype.kind != "f"
or not np.isfinite(w).all()
or np.any(w < 0)
or np.any(w[t == 255] != 0)
or a.dtype != bool
or a.shape != t.shape
or np.any(a & (t != 255))
):
raise ValueError("Only unknown pixels may become reviewed TRAIN background")
target = t.copy()
target[a] = 0
out.append(dict(r, target=target, context_added=a.copy()))
result[name] = w.copy()
for group in sorted({r["group"] for r in records}):
before = [r for r in records if r["group"] == group]
after = [r for r in out if r["group"] == group]
if not any(additions[r["name"]].any() for r in before):
continue
mass = sum(
float(weights[r["name"]][r["target"] == 0].sum(dtype=np.float64)) for r in before
)
present = [r for r in after if np.any(r["target"] == 0)]
if mass <= 0 or not present:
raise ValueError("Existing reviewed street background mass required")
for r in present:
mask = r["target"] == 0
result[r["name"]][mask] = mass / len(present) / int(mask.sum())
actual = sum(
float(result[r["name"]][r["target"] == 0].sum(dtype=np.float64)) for r in after
)
if not np.isclose(actual, mass, atol=1e-8, rtol=1e-6):
raise ValueError("Street background mass changed")
return out, result
def context_gate(old, new, control):
"""Frozen coverage screen; no thresholds or model selection after fitting."""
checks = {
"halve_context_fp": new["context_fp"] <= 0.5 * old["context_fp"],
"reduce_bce": new["bce"] < old["bce"],
"beat_control_bce": new["bce"] < control["bce"],
}
for key in ["original_fp", "prior_added_fp", "weak_fn", "clear_fn"]:
checks["retain_" + key] = new[key] <= old[key]
for key in ["background_fp", "weak_fn", "clear_fn"]:
checks["control_" + key] = new[key] <= control[key]
return {"passed": all(checks.values()), "checks": checks}
@@ -0,0 +1,381 @@
"""Frozen Worker corpus index over existing portable semantic review datasets.
Only metadata is indexed. Samples keep all views, cameras and labels together;
no image copy, model fitting or automatic training admission occurs here.
Groups are explicit experiment/source-lineage assignments; one unnamed scan
may have its own group. This reader performs no geographic or cross-scan
matching and requires no GPS/overlap proof. Group IDs do not prove independence.
"""
import argparse
import hashlib
import json
import shutil
import sqlite3
import tempfile
from contextlib import contextmanager
from pathlib import Path
from dataset_store import checksum, confined, digest, review_labels, sample_records
SCHEMA = "missioncore.semantic-corpus/v1"
PLAN_SCHEMA = "missioncore.semantic-corpus-plan/v1"
SPLITS = {"train", "validation", "test", "regression"}
MAX_METADATA = 8 * 1024**2
MAX_SAMPLE_METADATA = 24 * 1024**2
MAX_DATASETS = 2048
MAX_REFERENCE = 256 * 1024
MAX_BATCH_BYTES = 2 * 1024**2
MAX_INDEX_BYTES = 256 * 1024**2
def load_json(path, limit=MAX_METADATA):
with Path(path).open("rb") as stream:
raw = stream.read(limit + 1)
if len(raw) > limit:
raise ValueError("Corpus metadata budget exceeded")
return json.loads(raw)
def sha256(value):
if (
not isinstance(value, str)
or len(value) != 64
or any(c not in "0123456789abcdef" for c in value)
):
raise ValueError("Invalid SHA-256 identity")
return value
def assignments(plan):
if plan.get("schema_version") != PLAN_SCHEMA:
raise ValueError("Unsupported corpus plan")
result, groups = {}, set()
for group in plan["groups"]:
name, split = group["id"], group["split"]
if (
not isinstance(name, str)
or not name
or len(name) > 128
or name in groups
or split not in SPLITS
):
raise ValueError("Invalid or duplicate physical group")
groups.add(name)
if not group["worlds"]:
raise ValueError("Empty physical group")
for world in group["worlds"]:
sha256(world)
if world in result:
raise ValueError("One source world assigned to multiple physical groups")
result[world] = dict(physical_group=name, split=split)
if not 1 <= len(result) <= MAX_DATASETS:
raise ValueError("Corpus source-group budget exceeded")
return dict(sorted(result.items()))
def checked_file(root, name, spec):
path = confined(Path(root), name)
if path.stat().st_size != spec["bytes"] or checksum(path) != spec["sha256"]:
raise ValueError("Pinned corpus member changed: " + name)
return path
def build(store, plan, destination):
"""Build beside datasets; publish corpus.json last as the completion marker."""
store = Path(store).resolve()
destination = confined(store, destination)
if destination.exists():
raise ValueError("Corpus version already exists")
policy = assignments(plan)
datasets = sorted(plan["datasets"], key=lambda d: d["path"])
if not 1 <= len(datasets) <= MAX_DATASETS:
raise ValueError("Corpus dataset budget exceeded")
identities, paths = set(), set()
for entry in datasets:
sha256(entry["sha256"])
path = confined(store, entry["path"])
if path in paths or entry["sha256"] in identities:
raise ValueError("Duplicate corpus dataset")
paths.add(path)
identities.add(entry["sha256"])
if destination.is_relative_to(path) or path.is_relative_to(destination):
raise ValueError("Corpus output overlaps immutable input")
if checksum(path / "dataset.json") != entry["sha256"]:
raise ValueError("Pinned dataset manifest changed")
parent = plan.get("parent")
if parent:
with Corpus(store, parent["path"], parent["sha256"]) as prior:
if any(policy.get(w) != a for w, a in prior.manifest["assignments"].items()):
raise ValueError("Growth cannot change prior physical splits")
previous = {(d["path"], d["sha256"]) for d in prior.manifest["datasets"]}
if not previous <= {(d["path"], d["sha256"]) for d in datasets}:
raise ValueError("Growth cannot silently discard prior datasets")
destination.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix=".corpus-", dir=destination.parent) as temporary:
staging = Path(temporary) / "published"
staging.mkdir()
db = sqlite3.connect(staging / "index.sqlite3")
try:
page_size = db.execute("PRAGMA page_size").fetchone()[0]
db.execute(f"PRAGMA max_page_count={max(1, MAX_INDEX_BYTES // page_size)}")
db.executescript("""
CREATE TABLE samples (
id TEXT PRIMARY KEY, dataset TEXT NOT NULL, physical_group TEXT NOT NULL,
split TEXT NOT NULL, reference TEXT NOT NULL
);
CREATE INDEX by_split ON samples(split, physical_group, id);
""")
split_groups = {}
for entry in datasets:
root = confined(store, entry["path"])
count = 0
for row in sample_records(root):
source = row["source"]
assignment = policy.get(source["world_sha256"])
if assignment is None:
raise ValueError("Missing physical-area assignment for source")
# Preserve explicitly declared producer lineage without inferring
# geographic relationships between different scans.
previous = split_groups.setdefault(source["split_group"], assignment)
if previous != assignment:
raise ValueError("Related source split_group crosses physical groups")
identity = digest([entry["sha256"], row["sample"]])
reference = dict(
id=identity,
dataset=entry["path"],
dataset_sha256=entry["sha256"],
**assignment,
**row,
training_eligible=False,
)
encoded = json.dumps(reference, sort_keys=True, allow_nan=False)
if len(encoded.encode()) > MAX_REFERENCE:
raise ValueError("Sample reference budget exceeded")
db.execute(
"INSERT INTO samples VALUES (?,?,?,?,?)",
(
identity,
entry["path"],
assignment["physical_group"],
assignment["split"],
encoded,
),
)
count += 1
if not count:
raise ValueError("Empty corpus dataset")
if checksum(root / "dataset.json") != entry["sha256"]:
raise ValueError("Dataset changed during indexing")
db.commit()
counts = {
s: n for s, n in db.execute("SELECT split,count(*) FROM samples GROUP BY split")
}
except sqlite3.OperationalError as exc:
if exc.sqlite_errorcode == sqlite3.SQLITE_FULL:
raise ValueError("Corpus index or disk capacity exhausted") from exc
raise
finally:
db.close()
for name in ("corpus_store.py", "dataset_store.py"):
shutil.copyfile(Path(__file__).with_name(name), staging / name)
manifest = dict(
schema_version=SCHEMA,
plan_sha256=digest(plan),
assignments=policy,
datasets=datasets,
parent=parent,
sample_counts=counts,
training_eligible=False,
files={
p.name: dict(sha256=checksum(p), bytes=p.stat().st_size)
for p in sorted(staging.iterdir())
},
)
encoded = json.dumps(manifest, sort_keys=True, indent=2, allow_nan=False)
if len(encoded.encode()) > MAX_METADATA:
raise ValueError("Corpus manifest budget exceeded")
(staging / "corpus.json").write_text(encoded)
# Never overwrite a published corpus, including an empty existing folder.
destination.mkdir()
try:
for name in manifest["files"]:
(staging / name).replace(destination / name)
(staging / "corpus.json").replace(destination / "corpus.json")
except BaseException:
shutil.rmtree(destination)
raise
return dict(
path=destination.relative_to(store).as_posix(),
sha256=checksum(destination / "corpus.json"),
sample_counts=counts,
)
class Corpus:
"""Read-only, pinned index with bounded metadata batches and explicit media reads."""
def __init__(self, store, corpus, expected_sha256):
self.store = Path(store).resolve()
self.root = confined(self.store, corpus)
if checksum(self.root / "corpus.json") != sha256(expected_sha256):
raise ValueError("Pinned corpus manifest changed")
self.sha256 = expected_sha256
self.manifest = load_json(self.root / "corpus.json")
if (
self.manifest.get("schema_version") != SCHEMA
or self.manifest.get("training_eligible") is not False
):
raise ValueError("Unsupported corpus review policy")
for name, spec in self.manifest["files"].items():
checked_file(self.root, name, spec)
index = confined(self.root, "index.sqlite3")
if "index.sqlite3" not in self.manifest["files"]:
raise ValueError("Unbound corpus index")
self.db = sqlite3.connect(index.as_uri() + "?mode=ro&immutable=1", uri=True)
self.db.execute("PRAGMA query_only=ON")
self.db.execute("PRAGMA cache_size=-1024")
self.db.execute("PRAGMA temp_store=FILE")
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def close(self):
self.db.close()
def batches(self, split, batch_size=8, *, physical_group=None):
"""Yield metadata only; caller explicitly opens the current sample's media.
This is deterministic traversal, not a class-balanced training sampler.
Batch size limits references in this reader, not objects retained by a caller.
"""
if split not in SPLITS or type(batch_size) is not int or not 1 <= batch_size <= 128:
raise ValueError("Invalid corpus split or batch size")
sql = "SELECT reference FROM samples WHERE split=?"
params = [split]
if physical_group is not None:
sql += " AND physical_group=?"
params.append(physical_group)
sql += " ORDER BY physical_group,id"
cursor = self.db.execute(sql, params)
try:
batch, size = [], 0
for (encoded,) in cursor:
length = len(encoded.encode())
if length > min(MAX_REFERENCE, MAX_BATCH_BYTES):
raise ValueError("Sample reference budget exceeded")
if batch and (len(batch) >= batch_size or size + length > MAX_BATCH_BYTES):
yield batch
batch, size = [], 0
batch.append(json.loads(encoded))
size += length
if batch:
yield batch
finally:
cursor.close()
def reference(self, sample_id):
"""Resolve one bound sample without enumerating other samples or media."""
row = self.db.execute(
"SELECT reference FROM samples WHERE id=?", (sha256(sample_id),)
).fetchone()
if row is None:
raise ValueError("Unknown corpus sample")
return json.loads(row[0])
def _reference(self, reference):
row = self.db.execute(
"SELECT reference FROM samples WHERE id=?", (reference["id"],)
).fetchone()
if row is None or json.loads(row[0]) != reference:
raise ValueError("Reference does not belong to this pinned corpus")
root = confined(self.store, reference["dataset"])
if checksum(root / "dataset.json") != reference["dataset_sha256"]:
raise ValueError("Pinned dataset manifest changed")
return root
def review(self, reference):
"""Load one sample's metadata/labels; no automatic training targets."""
root = self._reference(reference)
sample = load_json(
checked_file(root, reference["sample"], reference["sample_spec"]), MAX_SAMPLE_METADATA
)
labels = load_json(
checked_file(root, reference["labels"], reference["members"][reference["labels"]]),
MAX_SAMPLE_METADATA,
)
return dict(reference=reference, context=sample, **review_labels(labels))
@contextmanager
def open_member(self, reference, name):
"""Verify and stream one declared view/camera/mask; never scan the corpus."""
root = self._reference(reference)
if name not in reference["members"]:
raise ValueError("Unbound sample member")
path = confined(root, name)
spec = reference["members"][name]
with path.open("rb") as stream:
length = stream.seek(0, 2)
stream.seek(0)
actual = hashlib.file_digest(stream, "sha256").hexdigest()
if length != spec["bytes"] or actual != spec["sha256"]:
raise ValueError("Pinned corpus member changed: " + name)
stream.seek(0)
yield stream
def main():
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
make = commands.add_parser(
"build", help="Freeze an explicit multi-area review corpus on Worker"
)
make.add_argument("store", type=Path)
make.add_argument("plan", type=Path)
make.add_argument("destination", help="New corpus path relative to the portable store")
inspect = commands.add_parser("inspect", help="Read bounded metadata from a pinned corpus")
inspect.add_argument("store", type=Path)
inspect.add_argument("corpus")
inspect.add_argument("sha256")
inspect.add_argument("--split", choices=sorted(SPLITS), required=True)
inspect.add_argument("--limit", type=int, default=8)
args = parser.parse_args()
if args.command == "build":
print(json.dumps(build(args.store, load_json(args.plan), args.destination)))
else:
if not 1 <= args.limit <= 128:
raise ValueError("Inspection limit must be from 1 to 128")
with Corpus(args.store, args.corpus, args.sha256) as corpus:
batches = corpus.batches(args.split, batch_size=args.limit)
try:
rows = next(batches, [])
finally:
batches.close()
print(
json.dumps(
dict(
samples=[
{
k: r[k]
for k in (
"id",
"dataset",
"sample",
"physical_group",
"split",
"training_eligible",
)
}
for r in rows
],
total=corpus.manifest["sample_counts"].get(args.split, 0),
)
)
)
if __name__ == "__main__":
main()
@@ -0,0 +1,345 @@
"""Controlled label-coverage experiment. Offline; no production map writes."""
import json
import sys
from collections import Counter, defaultdict
from pathlib import Path
import numpy as np
from c4_admission_study import loaded
from grouped_selection_study import objective, select, transfer_gate
from object_assembly_study import measured
from object_proposal_study import labels, overlap, save_new, sha, timestamp
from paint_hypothesis_study import fit_classifier
from shapely.geometry import shape
from shapely.ops import unary_union
from visual_admission_study import check_inputs, evaluation, fit_head, predict, rank
def expanded_labels(candidates, reviewed):
result = labels(candidates, reviewed)
background = unary_union([shape(g) for g in reviewed.get("complete_background", [])])
for i, c in enumerate(candidates):
p = shape(c["geometry"])
if (
result[i] < 0
and not background.is_empty
and p.area > 0
and p.intersection(background).area / p.area >= 0.9
):
result[i] = 0
return result
def training_records(records, arm):
return [
r
for r in records
if r["split"] == "development" and (arm == "expanded" or "-coverage-" not in r["id"])
]
def fit(records, review, data, l2, expanded):
if not expanded:
return fit_head(records, review, data, "c4_512", l2)
x, y = [], []
for r in records:
ls = expanded_labels(r["variants"]["retained"], review[r["id"]])
x.append(data[r["id"]]["c4_512"][ls >= 0])
y.append(ls[ls >= 0])
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.update(positive=int(sum(yy == 1)), negative=int(sum(yy == 0)))
return model
def partial_gate(baseline, candidate):
found = {
o["id"]
for r in candidate["rows"]
for o in r["clipped_components"]["objects"]
if o["matched"]
}
return [
o["id"]
for r in baseline["rows"]
for o in r["clipped_components"]["objects"]
if o["matched"] and o["id"] not in found
]
def freeze(root):
protocol = dict(
**timestamp(),
session="coverage-admission-20261022",
hypothesis=(
"Does corrected and expanded raw-reviewed supervision improve unchanged "
"C4 candidate admission?"
),
scope=(
"Offline linear paint/background coverage. No map publication, topology "
"completion or full pipeline claim."
),
arms=["old104", "expanded"],
regularization=[0.01, 0.1, 1.0],
thresholds=[i / 20 for i in range(1, 20)],
development=(
"17 previous +12 new windows, same6 development streets; controls "
"excluded from every fit."
),
controls=(
"31 exposed regression +6 new raw-only windows >=18m from prior "
"same-street centers.2 control streets never fit."
),
annotations=(
"18 new windows inspected raw and overlay before fitting.54 full or "
"clipped objects.9 old negative region corrections; ambiguous scan "
"patches unknown.Original104 labels preserved for comparator.Explicit "
"background used only expanded training and both-arm evaluation."
),
representation=(
"Immutable installed Mask2FormerMapillary65; unchanged uniform C4 mean "
"of512 inside/ring descriptors. No backbone fine-tuning."
),
training=(
"Same balanced logistic500L-BFGS, training-fold normalization,6-fold "
"leave-street-out. No street IDs as features."
),
selection=(
"Zero reviewed OOF false positives; maximize worst street complete "
"matchable recall, macrofamily, found; lower median tied threshold; "
"regularization ties strongerL2. Exactly same selection in both arms."
),
acceptance=(
"Expanded must preserve every matched whole identity of old14 and old104 "
"C4 in BOTH cohorts; no extra reviewedFP on each street; strict gain in "
"each cohort; no lost clipped matched identity. Report failures without "
"tuning on controls."
),
limitations=(
"Single reviewer, sparse/unknown boundaries, few control streets; "
"geometric labels approximate, objects may duplicate proposals. New full "
"and clipped linear positives should cover>=3development streets; "
"otherwise coverage hypothesis is unqualified."
),
visual=(
"Inspect new18 annotations, all37 controls with acceptance overlays after "
"frozen evaluation. Keep2proofs."
),
resources=(
"Worker006 only, fixed installedimage, no network,3CPU8GiBGPU batch1,12GiBfree reserve."
),
retention=(
"Content-addressed verified textarchive, inventoried removal of "
"derivedmedia/arrays,2proofimages only; raw/models/acceptedmaps "
"preserved."
),
)
save_new(root / "protocol.json", protocol)
save_new(
root / "review-original.json",
json.loads(Path("/c4study/review-audit-corrected.json").read_text()),
)
save_new(root / "review-frozen.json", json.loads((root / "review-draft.json").read_text()))
names = [
"protocol.json",
"review-original.json",
"review-frozen.json",
"inputs.json",
"model-inventory.json",
]
names += [p.name for p in root.glob("*.py")]
names += [str(p.relative_to(root)) for p in (root / "data").iterdir()]
save_new(root / "input-hashes.json", {n: sha(root / n) for n in sorted(names)})
print("frozen", len(names))
def audit(root):
check_inputs(root)
records = json.loads((root / "candidates.json").read_text())["records"]
old = {a["id"]: a for a in json.loads(Path("/c4study/candidates.json").read_text())["records"]}
original = json.loads((root / "review-original.json").read_text())["records"]
review = json.loads((root / "review-frozen.json").read_text())["records"]
changes = []
counts = defaultdict(Counter)
families = defaultdict(lambda: defaultdict(Counter))
compared = 0
for r in records:
cs = r["variants"]["retained"]
rid = r["id"]
if rid in old:
assert cs == old[rid]["variants"]["retained"], rid
compared += 1
if r["split"] != "development":
continue
new = expanded_labels(cs, review[rid])
for c, y in zip(cs, new, strict=True):
counts["expanded"][str(y)] += 1
if y == 1:
targets = review[rid]["objects"]
match = max(
targets, key=lambda o: overlap(shape(o["geometry"]), shape(c["geometry"]))
)
families["expanded"][match["family"]][r["street"]] += 1
if rid in original:
ls = labels(cs, original[rid])
for c, a, b in zip(cs, ls, new, strict=True):
counts["old104"][str(a)] += 1
if a != b:
changes.append(dict(window=rid, candidate=c["id"], old=int(a), new=int(b)))
assert counts["old104"]["1"] == 36 and counts["old104"]["0"] == 68, counts
assert compared == 48, compared
result = dict(
**timestamp(),
labels=counts,
families=families,
changes=changes,
old_candidate_windows_bitexact=compared,
)
save_new(root / "label-audit.json", result)
print(json.dumps(result))
def train(root):
check_inputs(root)
records, review, data = loaded(root)
original = json.loads((root / "review-original.json").read_text())["records"]
protocol = json.loads((root / "protocol.json").read_text())
arms = {}
for arm in protocol["arms"]:
dev = training_records(records, arm)
rr = review if arm == "expanded" else original
assert not ({r["street"] for r in dev} & {"pokrovka", "sadovaya-karetnaya"})
ceiling = {r["id"]: measured(r["variants"]["retained"], rr[r["id"]]) for r in dev}
experiments = []
for l2 in protocol["regularization"]:
scores = {}
folds = {}
for street in sorted({r["street"] for r in dev}):
tr = [r for r in dev if r["street"] != street]
va = [r for r in dev if r["street"] == street]
model = fit(tr, rr, data, l2, arm == "expanded")
scores.update(predict(va, data, "c4_512", model))
folds[street] = dict(training_ids=[r["id"] for r in tr], model=model)
sweep = []
for threshold in protocol["thresholds"]:
result = evaluation(dev, rr, scores, threshold)
sweep.append(
dict(
threshold=threshold,
**result["summary"],
**objective(result["rows"], ceiling),
)
)
experiments.append(dict(l2=l2, selected=select(sweep), 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
arms[arm] = dict(
selected=best["selected"] if best else None,
l2=best["l2"] if best else None,
model=fit(dev, rr, data, best["l2"], arm == "expanded") if best else None,
experiments=experiments,
)
print(
json.dumps(dict(arm=arm, l2=arms[arm]["l2"], selected=arms[arm]["selected"])),
flush=True,
)
save_new(
root / "models-frozen.json",
dict(
**timestamp(),
arms=arms,
hashes={
n: sha(root / n)
for n in [
"protocol.json",
"review-frozen.json",
"review-original.json",
"input-hashes.json",
"candidates.json",
"features.json",
"coverage_admission_study.py",
]
},
),
)
def evaluate(root):
check_inputs(root)
records, review, data = loaded(root)
frozen = json.loads((root / "models-frozen.json").read_text())
for n, h in frozen["hashes"].items():
assert sha(root / n) == h, n
ref = json.loads(Path("/objectstudy/models-frozen.json").read_text())["models"][
"shape_appearance"
]
prior = json.loads(Path("/c4study/models-frozen.json").read_text())["variants"]["c4_512"]
# Exact reproduction must precede interpretation of the new arm.
old = frozen["arms"]["old104"]
assert (
old["l2"] == prior["l2"] and old["selected"]["threshold"] == prior["selected"]["threshold"]
)
old_scores = predict(records, data, "c4_512", old["model"])
prior_scores = predict(records, data, "c4_512", prior["model"])
error = max(
[
abs(a - b)
for rid in old_scores
for a, b in zip(old_scores[rid], prior_scores[rid], strict=True)
],
default=0,
)
assert error < 1e-8, error
results = {}
gates = {}
for split in ["regression", "heldout"]:
subset = [r for r in records if r["split"] == split]
result = {}
result["old14"] = evaluation(
subset,
review,
predict(subset, data, "handcrafted14", ref["model"]),
ref["selected"]["threshold"],
)
for arm, info in frozen["arms"].items():
ps = (
predict(subset, data, "c4_512", info["model"])
if info["model"]
else {r["id"]: [0] * len(r["variants"]["retained"]) for r in subset}
)
result[arm] = evaluation(
subset, review, ps, info["selected"]["threshold"] if info["selected"] else 1
)
gates[split] = {}
for comparator in ["old14", "old104"]:
gate = transfer_gate(result[comparator], result["expanded"])
lost = partial_gate(result[comparator], result["expanded"])
gate.update(lost_clipped_objects=lost, passed=gate["passed"] and not lost)
gates[split][comparator] = gate
results[split] = result
out = dict(
**timestamp(),
results=results,
gates=gates,
passed=all(g["passed"] for split in gates.values() for g in split.values()),
old104_reproduction_max_score_error=error,
)
save_new(root / "results.json", out)
print(
json.dumps(
dict(
passed=out["passed"],
gates=gates,
summaries={
s: {a: v["summary"] for a, v in rr.items()} for s, rr in results.items()
},
)
)
)
if __name__ == "__main__":
globals()[sys.argv[1]](Path(sys.argv[2]) if len(sys.argv) > 2 else Path("/experiment"))
@@ -0,0 +1,114 @@
"""Training-label factorial with common held-out targets and non-compensating gates.
Offline diagnostic: exposed controls never select recipes; no production publication.
"""
import copy
import math
from transfer_gates import component_regressions
def learning_view(records, coverage):
"""Swap only training supervision, preserving the common evaluation records."""
if coverage not in ("old", "new") or any(r["split"] != "train" for r in records):
raise ValueError("Training records and registered coverage only")
key = "old_target" if coverage == "old" else "target"
return [dict(r, target=r[key]) for r in records]
def relabel_parent(rows, session):
result = copy.deepcopy(rows)
for r in result:
if r["arm"].startswith(("head-", "decoder-")):
r["arm"] = "new-" + r["arm"]
r["origin"] = session
return result
def assess(rows, seeds):
if not seeds or len(set(seeds)) != len(seeds):
raise ValueError("Unique preregistered seeds required")
expected = {"old-linear", "new-linear"} | {
f"{c}-{f}-{s}" for c in ("old", "new") for f in ("head", "decoder") for s in seeds
}
if not rows or any(r["phase"] != "development" for r in rows):
raise ValueError("Development only")
if {r["arm"] for r in rows} != expected:
raise ValueError("Incomplete factorial")
groups = {r["held_out"] for r in rows}
if len(groups) != 4:
raise ValueError("Four physical groups required")
summaries = {}
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/duplicate group")
if any(not r["completed"] or r["held_out"] in r["fitted_groups"] for r in rr):
raise ValueError("Incomplete or leaked fit")
errors = []
for r in rr:
m = r["metrics"]
if any(
m[k] is None or not math.isfinite(m[k]) or not 0 <= m[k] <= 1
for k in ("recall", "fpr")
):
raise ValueError("Both reviewed classes required")
errors.append((1 - m["recall"] + m["fpr"]) / 2)
summaries[arm] = dict(mean=sum(errors) / 4, worst=max(errors))
audits = []
eligible = []
for coverage in ("old", "new"):
for family in ("head", "decoder"):
failures = []
for seed in seeds:
arm = f"{coverage}-{family}-{seed}"
refs = {"old-linear", f"{coverage}-linear"}
if family == "decoder":
refs.add(f"{coverage}-head-{seed}")
for ref in sorted(refs):
a, b = summaries[arm], summaries[ref]
cc = component_regressions(rows, ref, [arm])
composite = a["mean"] < b["mean"] - 1e-12 and a["worst"] <= b["worst"] + 1e-12
check = dict(arm=arm, composite_pass=composite, **cc)
audits.append(check)
if not composite or not cc["all_components_non_regressing"]:
failures.append(check)
if not failures:
eligible.append(f"{coverage}-{family}")
return dict(
eligible_families=eligible,
summaries=summaries,
audits=audits,
all_seeds_required=True,
production_eligible=False,
control_selection=False,
)
def effects(rows, seeds):
"""Paired effects in metric fractions; descriptive, no pixel-independence CI."""
assess(rows, seeds)
by_key = {(r["held_out"], r["arm"]): r["metrics"] for r in rows}
result = []
for group in sorted({r["held_out"] for r in rows}):
for seed in seeds:
for metric in ("recall", "fpr"):
def val(coverage, family, group=group, seed=seed, metric=metric):
return by_key[(group, f"{coverage}-{family}-{seed}")][metric]
old_gain = val("old", "decoder") - val("old", "head")
new_gain = val("new", "decoder") - val("new", "head")
result.append(
dict(
group=group,
seed=seed,
metric=metric,
old_decoder_minus_head=old_gain,
new_decoder_minus_head=new_gain,
interaction=new_gain - old_gain,
new_minus_old_decoder=val("new", "decoder") - val("old", "decoder"),
)
)
return result
@@ -0,0 +1,80 @@
"""TRAIN-only coverage/mass controls with sample-stable augmentation.
No coordinates or per-street exceptions. Existing pixel labels are immutable.
"""
import hashlib
import json
import numpy as np
from spatial_decoder_probe import dense_weights
POLICIES = {"base", "equal_window", "mass"}
def prepare(records, policy):
if policy not in POLICIES or not records:
raise ValueError("Known policy and nonempty TRAIN records required")
ids, names = set(), set()
for r in records:
sid, name = r["sample_id"], r["name"]
if r["split"] != "train" or not sid or sid in ids or name in names:
raise ValueError("Unique TRAIN samples required")
ids.add(sid)
names.add(name)
t, old = r["target"], r["base_target"]
if (
t.dtype != np.uint8
or old.dtype != np.uint8
or t.ndim != 2
or t.shape != old.shape
or not np.isin(t, [0, 1, 255]).all()
or not np.isin(old, [0, 1, 255]).all()
):
raise ValueError("Aligned uint8 targets required")
if not np.array_equal(t[old != 255], old[old != 255]):
raise ValueError("Existing labels are immutable")
if not np.array_equal(t == 0, old == 0):
raise ValueError("This comparison admits paint only")
ordered = sorted(records, key=lambda r: r["sample_id"])
base = [dict(r, target=r["base_target"]) for r in ordered]
original = dense_weights(base)
if policy == "base":
return base, original
if policy == "equal_window":
return ordered, dense_weights(ordered)
weights = {name: w.copy() for name, w in original.items()}
for group in sorted({r["group"] for r in ordered}):
rr = [r for r in ordered if r["group"] == group]
old_count = sum(int((r["base_target"] == 1).sum()) for r in rr)
new_count = sum(int(((r["base_target"] == 255) & (r["target"] == 1)).sum()) for r in rr)
if not old_count:
raise ValueError("Every street needs original positive support")
if not new_count:
continue
mass = sum(
float(original[r["name"]][r["base_target"] == 1].sum(dtype=np.float64)) for r in rr
)
factor = old_count / (old_count + new_count)
for r in rr:
weights[r["name"]][r["base_target"] == 1] *= factor
added = (r["base_target"] == 255) & (r["target"] == 1)
weights[r["name"]][added] = mass / (old_count + new_count)
return ordered, weights
def rotation(seed, step, sample_id):
if not isinstance(seed, int) or not isinstance(step, int) or step < 0 or not sample_id:
raise ValueError("Integer seed/update and sample identity required")
payload = json.dumps(
["coverage-rotation-v1", seed, step, sample_id], separators=(",", ":")
).encode()
return hashlib.sha256(payload).digest()[0] % 4
def schedule_digest(records, seed, steps):
rows = [
(r["sample_id"], [rotation(seed, step, r["sample_id"]) for step in range(steps)])
for r in sorted(records, key=lambda r: r["sample_id"])
]
return hashlib.sha256(json.dumps(rows, separators=(",", ":")).encode()).hexdigest()
@@ -0,0 +1,195 @@
"""Bounded train-only sample-growth experiment with frozen exposed controls."""
import argparse
import time
from pathlib import Path
import numpy as np
from pixel_growth_probe import aggregate, counts, fit, resize_plane
from scipy.special import expit
from supervision_density_probe import check_pair, load_examples, samples
def check_expansion(old, new, before, after):
if not set(old) < set(new):
raise ValueError("Expected a strict sample expansion")
groups = {e["physical_group"] for e in old.values() if e["split"] == "train"}
seen_images = {i["rgb"]["sha256"] for e in old.values() for i in e["inputs"]}
for sid, e in old.items():
check_pair(e, new[sid], before[sid], after[sid])
if not np.array_equal(before[sid], after[sid]):
raise ValueError("Existing training targets changed")
for sid in set(new) - set(old):
e = new[sid]
if e["split"] != "train" or e["physical_group"] not in groups:
raise ValueError("Addition must belong to an existing training physical group")
if not {0, 1} <= set(np.unique(after[sid])):
raise ValueError("New crossing requires both paint and gap background")
for i in e["inputs"]:
if i["rgb"]["sha256"] in seen_images:
raise ValueError("Duplicate observation in added windows")
seen_images.add(i["rgb"]["sha256"])
def qualify(metrics, audit, reproduced):
failures = []
if not reproduced:
failures.append("baseline reproduction failed")
for group, variants in metrics.items():
for metric, sign in [("recall", 1), ("fpr", -1)]:
a, b = variants["baseline"][metric], variants["expanded"][metric]
if a is not None and b is not None and sign * (b - a) < -1e-12:
failures.append(group + ": " + metric)
if audit["expanded"]["recall"] < audit["baseline"]["recall"]:
failures.append("diagnostic paint recall")
if audit["expanded"]["fpr"] >= audit["baseline"]["fpr"]:
failures.append("diagnostic gap false positives not strictly reduced")
return dict(accepted=not failures, failures=failures)
def run(root, store):
import torch
from admission_store import pixel_target
from dataset_store import checksum, read, write
torch.set_num_threads(3)
start = time.monotonic()
assert not (root / "models-frozen.json").exists() and not (root / "result.json").exists()
protocol = read(root / "protocol.json")
frozen = read(root / "review-frozen.json")
manifest = read(root / "feature-manifest.json")
parent = store / "experiments" / protocol["parent"]
assert frozen["source_sha256"] == checksum(Path(__file__))
assert (
manifest["protocol_sha256"] == frozen["protocol_sha256"] == checksum(root / "protocol.json")
)
for key, name in [
("audit_sha256", "p1-audit-runs-final.json"),
("pixel_runs_sha256", "pixel-runs-final.json"),
("regions_sha256", "regions-final.json"),
]:
assert frozen[key] == checksum(root / name)
assert checksum(root / "model-inventory.json") == checksum(parent / "model-inventory.json")
params = protocol["fit"]
assert params == read(parent / "protocol.json")["fit"]
old_receipt = read(parent / "supervision-receipt.json")
assert old_receipt["sha256"] == protocol["parent_release_sha256"]
old, before = load_examples(store, old_receipt)
new, after = load_examples(store, read(root / "supervision-receipt.json"))
check_expansion(old, new, before, after)
assert set(new) == {r["sample_id"] for r in manifest["records"]}
assert {r["name"] for r in manifest["records"] if r["sample_id"] not in old} == set(
protocol["added_training_windows"]
)
units = {"baseline": [], "expanded": []}
for r in manifest["records"]:
sid = r["sample_id"]
assert checksum(root / r["cache"]) == r["sha256"]
with np.load(root / r["cache"]) as z:
assert np.array_equal(z["target"], after[sid])
if r["split"] == "train":
unit = samples(z["features"].astype("float32"), after[sid], r, params)
units["expanded"].append(unit)
if sid in old:
units["baseline"].append(unit)
models = {arm: fit(us, params["l2"], params["max_iterations"]) for arm, us in units.items()}
fit_seconds = time.monotonic() - start
write(
root / "models-frozen.json",
dict(
models=models,
threshold=params["threshold"],
protocol_sha256=checksum(root / "protocol.json"),
review_sha256=checksum(root / "review-frozen.json"),
features_sha256=checksum(root / "feature-manifest.json"),
source_sha256=checksum(Path(__file__)),
frozen_before_evaluation=True,
),
)
rows, train_rows, diagnostic = [], [], None
old_rows = {r["name"]: r for r in read(parent / "result.json")["rows"]}
for r in manifest["records"]:
# Training diagnostics are reported separately, never scored as transfer.
with np.load(root / r["cache"]) as z:
features, target = z["features"].astype("float32"), z["target"]
predictions = {}
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", features, scaled) + bias
predictions[arm] = (
expit(resize_plane(logits[None], target.shape)[0]) >= params["threshold"]
)
np.savez_compressed(root / "cache" / (r["name"] + "-predictions.npz"), **predictions)
row = dict(
name=r["name"],
group=r["group"],
variants={arm: counts(p, target) for arm, p in predictions.items()},
)
(rows if r["split"] == "regression" else train_rows).append(row)
if r["name"] == "P1":
t = read(root / "p1-audit-runs-final.json")
audit_target = np.frombuffer(
pixel_target(dict(t, size=[512, 512])), dtype="uint8"
).reshape(512, 512)
diagnostic = {
arm: aggregate([counts(p, audit_target)]) for arm, p in predictions.items()
}
assert diagnostic is not None
metrics = {
g: {arm: aggregate([r["variants"][arm] for r in rows if r["group"] == g]) for arm in models}
for g in sorted({r["group"] for r in rows})
}
reproduced_counts = all(
r["variants"]["baseline"] == old_rows[r["name"]]["variants"]["dense"] for r in rows
)
prior_model = read(parent / "models-frozen.json")["models"]["dense"]
delta = max(
float(np.max(np.abs(np.array(models["baseline"][k]) - np.array(prior_model[k]))))
for k in ["mean", "scale", "coefficients"]
)
outcome = qualify(metrics, diagnostic, reproduced_counts and delta == 0.0)
result = dict(
**outcome,
metrics=metrics,
rows=rows,
train_rows=train_rows,
diagnostic=diagnostic,
baseline_reproduced=reproduced_counts and delta == 0.0,
baseline_max_parameter_delta=delta,
models_sha256=checksum(root / "models-frozen.json"),
source_sha256=checksum(Path(__file__)),
protocol_sha256=checksum(root / "protocol.json"),
fit_and_load_seconds=fit_seconds,
total_seconds=time.monotonic() - start,
evaluated_utc=__import__("datetime")
.datetime.now(__import__("datetime").timezone.utc)
.isoformat(),
production_eligible=False,
blind_generalization_claim=False,
)
write(root / "result.json", result)
print(
__import__("json").dumps(
{
k: result[k]
for k in [
"accepted",
"failures",
"metrics",
"diagnostic",
"baseline_reproduced",
"baseline_max_parameter_delta",
]
}
)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("root", type=Path)
parser.add_argument("--store", type=Path, default=Path("/store"))
args = parser.parse_args()
run(args.root, args.store)
@@ -0,0 +1,430 @@
"""Worker-only bounded inbox and portable, hash-verified sample manifests (stdlib)."""
import hashlib
import json
import os
import shutil
import sqlite3
from pathlib import Path, PurePosixPath
SCHEMA = "missioncore.semantic-dataset/v1"
MAX_JOB = 24 * 1024**2
MAX_DATASET = 512 * 1024**2
def digest(value):
return hashlib.sha256(
json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False).encode()
).hexdigest()
def checksum(path):
with Path(path).open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def write(path, value):
path = Path(path)
raw = json.dumps(value, ensure_ascii=False, allow_nan=False).encode()
tmp = path.with_suffix(".tmp")
with tmp.open("wb") as stream:
stream.write(raw)
stream.flush()
os.fsync(stream.fileno())
os.replace(tmp, path)
def read(path):
return json.loads(Path(path).read_text(encoding="utf-8"))
def confined(root, name):
rel = PurePosixPath(name)
if (
not rel.parts
or rel.is_absolute()
or ".." in rel.parts
or "\\" in name
or ":" in name
or rel.as_posix() != name
):
raise ValueError("Unsafe dataset member")
path = root.joinpath(*rel.parts)
if path.is_symlink() or not path.resolve().is_relative_to(root.resolve()):
raise ValueError("Dataset member escaped root")
return path
def verify(root):
root = Path(root)
manifest = read(root / "dataset.json")
if manifest["schema_version"] == "missioncore.semantic-collection/v1":
if (
manifest.get("training_eligible") is not False
or not 1 <= len(manifest["shards"]) <= 256
):
raise ValueError("Invalid collection review policy")
total = count = 0
expected = {"dataset.json", *manifest["files"]}
for name, spec in manifest["files"].items():
p = confined(root, name)
if p.stat().st_size != spec["bytes"] or checksum(p) != spec["sha256"]:
raise ValueError("Collection file changed")
total += spec["bytes"]
for name, spec in manifest["shards"].items():
child = confined(root, name)
if read(child / "dataset.json")["schema_version"] != SCHEMA:
raise ValueError("Nested collections forbidden")
result = verify(child)
if result != spec:
raise ValueError("Collection shard changed")
count += result["sample_count"]
total += result["bytes"]
expected.update(p.relative_to(root).as_posix() for p in child.rglob("*") if p.is_file())
if (
total > 4 * 1024**3
or {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()} != expected
):
raise ValueError("Collection size or membership changed")
return dict(
sha256=checksum(root / "dataset.json"),
sample_count=count,
bytes=total,
training_eligible=False,
)
if manifest["schema_version"] != SCHEMA or manifest["training_eligible"] is not False:
raise ValueError("Unsupported dataset review policy")
total = 0
for name, spec in manifest["files"].items():
path = confined(root, name)
total += spec["bytes"]
if (
total > MAX_DATASET
or path.stat().st_size != spec["bytes"]
or checksum(path) != spec["sha256"]
):
raise ValueError("Dataset integrity check failed: " + name)
actual = {p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()}
if actual != set(manifest["files"]) | {"dataset.json"}:
raise ValueError("Unmanifested dataset contents")
for sample in manifest["samples"]:
row = read(confined(root, sample))
for name in row["members"]:
if name not in manifest["files"]:
raise ValueError("Unbound sample member")
if row["training_eligible"] or row["complete_regions"]:
raise ValueError("Unreviewed edit cannot provide training ground truth")
return {
"sha256": checksum(root / "dataset.json"),
"sample_count": len(manifest["samples"]),
"bytes": total,
"training_eligible": False,
}
def review_labels(labels):
"""Separate retained history from current candidates. Neither is training truth.
Editor 'accepted' is a map review status, not per-view training admission.
Projection flags/opaque pixels likewise do not prove visual evidence.
"""
features = labels["proposed_element"]
by_id = {f["id"]: f for f in features}
if len(by_id) != len(features):
raise ValueError("Duplicate feature identity in review sample")
active, rejected = [], []
for f in features:
status = f["properties"].get("review_status", "unreviewed")
if status not in {"unreviewed", "accepted", "rejected"}:
raise ValueError("Unknown map review status")
(rejected if status == "rejected" else active).append(f)
active_ids = {f["id"] for f in active}
views = {}
for name, projections in labels["projections"].items():
if any(p["feature_id"] not in by_id for p in projections):
raise ValueError("Projection references an unknown feature")
views[name] = dict(
candidate_projections=[p for p in projections if p["feature_id"] in active_ids],
rejected_projections=[p for p in projections if p["feature_id"] not in active_ids],
evidence="unreviewed",
approved_targets=[],
complete_regions=[],
training_eligible=False,
)
return dict(
original=labels["original_element"],
active_candidates=active,
rejected_history=rejected,
approved_targets=[],
background_targets=[],
views=views,
training_eligible=False,
)
def sample_records(root):
"""Yield bound context/member references; never decode or collect image arrays."""
root = Path(root)
verify(root)
manifest = read(root / "dataset.json")
children = (
[(name, confined(root, name)) for name in manifest["shards"]]
if manifest["schema_version"] == "missioncore.semantic-collection/v1"
else [("", root)]
)
annotation = manifest.get("annotation_sha256")
for prefix, child in children:
shard = read(child / "dataset.json")
for key in ("world_sha256", "revision", "split_group"):
if not shard.get(key) or shard[key] != manifest.get(key):
raise ValueError("Review shard source identity mismatch: " + key)
annotation = annotation or shard.get("annotation_sha256")
if not annotation or annotation != shard.get("annotation_sha256"):
raise ValueError("Review shard annotation identity mismatch")
source = {
k: shard[k] for k in ("world_sha256", "revision", "annotation_sha256", "split_group")
}
for name in shard["samples"]:
sample = read(confined(child, name))
label_name = str(PurePosixPath(name).with_name("labels.json"))
if label_name not in sample["members"]:
raise ValueError("Sample has no bound labels")
if (
sample["revision"] != shard["revision"]
or sample["split_group"] != shard["split_group"]
):
raise ValueError("Sample source identity mismatch")
yield dict(
source=source,
sample=str(PurePosixPath(prefix) / name),
labels=str(PurePosixPath(prefix) / label_name),
sample_spec=shard["files"][name],
members={
str(PurePosixPath(prefix) / member): shard["files"][member]
for member in sample["members"]
},
)
def review_samples(root):
"""Read verified portable observations without merging history into targets."""
root = Path(root)
for row in sample_records(root):
yield dict(
source=row["source"],
sample=row["sample"],
labels=row["labels"],
**review_labels(read(confined(root, row["labels"]))),
)
def review_index(root):
"""Small relative-path index. Existing datasets remain immutable; no RGB copy."""
root = Path(root)
source = None
samples, active, rejected, identities = [], set(), set(), {}
for row in review_samples(root):
source = row["source"]
partitions = {}
for key, ids in (("active_candidates", active), ("rejected_history", rejected)):
partitions[key] = [f["id"] for f in row[key]]
for f in row[key]:
identity = digest(f)
if f["id"] in identities and identities[f["id"]] != identity:
raise ValueError("Feature changed between review windows")
identities[f["id"]] = identity
ids.add(f["id"])
samples.append(
dict(
sample=row["sample"],
labels=row["labels"],
**partitions,
views={
name: dict(
evidence="unreviewed",
approved_targets=[],
complete_regions=[],
training_eligible=False,
)
for name in row["views"]
},
approved_targets=[],
background_targets=[],
training_eligible=False,
)
)
if source is None:
raise ValueError("Empty review dataset")
if active & rejected:
raise ValueError("Conflicting feature lifecycle between windows")
return dict(
schema_version="missioncore.semantic-review-index/v1",
dataset_sha256=checksum(root / "dataset.json"),
reader_sha256=checksum(__file__),
source=source,
samples=samples,
active_candidate_ids=sorted(active),
rejected_history_ids=sorted(rejected),
approved_targets=[],
background_targets=[],
training_eligible=False,
)
class Store:
def __init__(self, root, *, quota=20 * 1024**3, reserve=12 * 1024**3):
self.root, self.quota, self.reserve = Path(root), quota, reserve
self.root.mkdir(parents=True, exist_ok=True)
for folder in ("inbox", "datasets", "work", "sources", "logs"):
(self.root / folder).mkdir(exist_ok=True)
self.db = sqlite3.connect(self.root / "queue.sqlite3")
self.db.execute("PRAGMA synchronous=FULL")
self.db.execute("""CREATE TABLE IF NOT EXISTS jobs (
id TEXT PRIMARY KEY, identity TEXT NOT NULL, state TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
receipt TEXT NOT NULL, error TEXT, acknowledged TEXT)""")
self.db.commit()
def capacity(self, additional):
used = sum(p.stat().st_size for p in self.root.rglob("*") if p.is_file())
if (
used + additional > self.quota
or shutil.disk_usage(self.root).free < self.reserve + additional
):
raise RuntimeError("Worker learning storage quota/reserve reached")
def accept(self, envelope):
exported = envelope["annotation"]
package = exported["package"]
identity = exported["sha256"]
if identity != digest(package):
raise ValueError("Annotation checksum mismatch")
revision = package["revision"]
if len(revision) != 64 or any(c not in "0123456789abcdef" for c in revision):
raise ValueError("Invalid revision identity")
if (
package["world_sha256"] != envelope["world"]["sha256"]
or package["world_sha256"] != envelope["source"]["world_sha256"]
):
raise ValueError("Source does not belong to annotation world")
parent = None
for row in package["revisions"]:
if (
row["parent"] != parent
or digest({k: v for k, v in row.items() if k != "revision"}) != row["revision"]
):
raise ValueError("Annotation history changed")
parent = row["revision"]
if parent != revision or digest(package["model"]) != package["model_sha256"]:
raise ValueError("Annotation baseline changed")
previous = self.db.execute("SELECT identity FROM jobs WHERE id=?", (revision,)).fetchone()
if previous:
if previous[0] != identity:
raise ValueError("Conflicting annotation identity")
return revision
raw_size = len(json.dumps(envelope).encode())
if raw_size > MAX_JOB:
raise ValueError("Annotation exceeds inbox limit")
if (
self.db.execute(
"SELECT count(*) FROM jobs WHERE state NOT IN ('draft-ready','failed')"
).fetchone()[0]
>= 20
):
raise RuntimeError("Worker learning queue is full")
self.capacity(raw_size + 1024**2)
path = self.root / "inbox" / (revision + ".json")
if path.exists() and read(path) != envelope:
raise ValueError("Conflicting recovered inbox item")
write(path, envelope) # Durable file first; a crash before SQL is safe to replay.
receipt = dict(
state="received", package_sha256=identity, dataset_sha256=None, sample_count=0
)
with self.db:
self.db.execute(
"INSERT INTO jobs(id,identity,state,receipt) VALUES(?,?,?,?)",
(revision, identity, "received", json.dumps(receipt)),
)
return revision
def update(self, key, state, result=None, error=None):
identity = self.db.execute("SELECT identity FROM jobs WHERE id=?", (key,)).fetchone()[0]
receipt = dict(
state=state,
package_sha256=identity,
dataset_sha256=result["sha256"] if result else None,
sample_count=result["sample_count"] if result else 0,
)
with self.db:
self.db.execute(
"UPDATE jobs SET state=?,receipt=?,error=? WHERE id=?",
(state, json.dumps(receipt), error, key),
)
return receipt
def next(self):
row = self.db.execute(
"SELECT id,attempts FROM jobs WHERE state IN ('received','building') "
"ORDER BY rowid LIMIT 1"
).fetchone()
if not row:
return None
key, attempts = row
destination = self.root / "datasets" / key
if destination.exists():
try:
result = verify(destination)
except (ValueError, OSError, KeyError) as exc:
self.update(key, "failed", error="Published integrity failure: " + str(exc)[:1000])
else:
self.update(key, "draft-ready", result)
return None
if attempts >= 3:
self.update(key, "failed", error="Interrupted three times; explicit repair required")
return None
with self.db:
self.db.execute("UPDATE jobs SET attempts=attempts+1 WHERE id=?", (key,))
self.update(key, "building")
return key
def publish(self, key, staging):
result = verify(staging)
destination = self.root / "datasets" / key
if destination.exists():
if verify(destination) != result:
raise ValueError("Published dataset is immutable")
else:
os.replace(staging, destination)
self.update(key, "draft-ready", result)
return result
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Verify a portable semantic review dataset")
parser.add_argument("dataset", type=Path)
parser.add_argument(
"--review-index", type=Path, help="Write a separate review index, never training labels"
)
args = parser.parse_args()
if args.review_index:
destination = args.review_index.resolve()
if destination.is_relative_to(args.dataset.resolve()) or destination.exists():
raise ValueError("Review index must be new and outside the immutable dataset")
index = review_index(args.dataset)
write(destination, index)
print(
json.dumps(
dict(
samples=len(index["samples"]),
active=len(index["active_candidate_ids"]),
rejected=len(index["rejected_history_ids"]),
approved=0,
dataset_sha256=index["dataset_sha256"],
training_eligible=False,
)
)
)
else:
print(json.dumps(verify(args.dataset)))
@@ -0,0 +1,531 @@
"""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)
@@ -0,0 +1,89 @@
"""Bounded native-detail residual probe; no coordinates or location-specific rules."""
def network(seed):
import torch
from torch import nn
torch.manual_seed(seed)
net = nn.Sequential(
nn.Conv2d(4, 16, 3, padding=1),
nn.ReLU(),
nn.Conv2d(16, 16, 3, padding=1),
nn.ReLU(),
nn.Conv2d(16, 1, 1),
)
nn.init.zeros_(net[-1].weight)
nn.init.zeros_(net[-1].bias)
return net
def inputs(coarse, rgb, arm):
import torch
if arm not in {"coarse_only", "native_rgb"}:
raise ValueError("Unknown refinement arm")
if (
coarse.ndim != 4
or coarse.shape[1] != 1
or rgb.shape != (coarse.shape[0], 3, *coarse.shape[-2:])
or coarse.dtype != torch.float32
or rgb.dtype != torch.uint8
or coarse.requires_grad
or coarse.device != rgb.device
or not torch.isfinite(coarse).all()
):
raise ValueError("Aligned detached float32 scores and native uint8 RGB required")
fine = (
rgb.float().div(127.5).sub(1)
if arm == "native_rgb"
else torch.zeros_like(rgb, dtype=torch.float32)
)
return torch.cat((coarse, fine), dim=1)
def residual(net, x, tile=None):
"""Two 3x3 layers require a two-pixel halo. No resize or boundary averaging."""
if tile is None:
return net(x)
if not isinstance(tile, int) or isinstance(tile, bool) or tile < 1:
raise ValueError("Positive integer tile size required")
import torch
h, w = x.shape[-2:]
out = torch.empty((x.shape[0], 1, h, w), dtype=x.dtype, device=x.device)
for y in range(0, h, tile):
for xx in range(0, w, tile):
y1, x1 = min(y + tile, h), min(xx + tile, w)
sy, sx, ey, ex = max(0, y - 2), max(0, xx - 2), min(h, y1 + 2), min(w, x1 + 2)
patch = net(x[..., sy:ey, sx:ex])
out[..., y:y1, xx:x1] = patch[..., y - sy : y1 - sy, xx - sx : x1 - sx]
return out
def prediction(net, coarse, x, tile=None):
"""Add once after C4 residual averaging, preserving exact zero identity."""
import torch
correction = torch.stack(
[
torch.rot90(residual(net, torch.rot90(x, k, [-2, -1]), tile), -k, [-2, -1])
for k in range(4)
]
).mean(0)
return coarse + correction
def validate_groups(records, held, groups, parent_groups):
expected = set(groups) - {held}
if held not in groups or len(set(groups)) != len(groups) or set(parent_groups) != expected:
raise ValueError("Parent must exclude the whole held street")
ids = [r["sample_id"] for r in records]
if (
not records
or len(set(ids)) != len(ids)
or not all(ids)
or any(r["split"] != "train" or r["group"] == held for r in records)
or {r["group"] for r in records} != expected
):
raise ValueError("Unique TRAIN records from exactly the allowed streets required")
@@ -0,0 +1,186 @@
"""Fixed class/family/frame/pixel mass and deterministic point budgets.
The caller supplies the complete source-group to exclusion-family mapping,
filters the held family and validates source/target admission before this helper.
Original group and split metadata are preserved. A mapping must cover all study
families, even when one arm contains no frames from some of its source groups.
"""
from collections.abc import Mapping
import numpy as np
def _identity(value):
return isinstance(value, str) and bool(value)
def prepare(records, held_family, family_by_group):
"""Return sample-sorted record copies, float64 weights and JSON mass audit.
Each class receives .5 total mass, divided equally among allowed families,
then among frames supporting that class, then among its pixels. Every
allowed family must support both classes, but a frame may support only one.
Unknown-only frames cannot receive positive sampling quotas and are rejected.
Record dicts and targets are copied; unrelated payloads are shared untouched.
"""
if (
not _identity(held_family)
or not isinstance(family_by_group, Mapping)
or not family_by_group
or any(not _identity(g) or not _identity(f) for g, f in family_by_group.items())
):
raise ValueError("Explicit nonempty source-group/family mapping required")
families = set(family_by_group.values())
if held_family not in families:
raise ValueError("Held family must be present in the study mapping")
allowed = sorted(families - {held_family})
records = list(records)
if not records or not allowed:
raise ValueError("Nonempty records and allowed families required")
names, samples, observed = set(), set(), set()
for record in records:
if not isinstance(record, Mapping) or any(
not _identity(record.get(key)) for key in ("name", "sample_id", "group")
):
raise ValueError("Record name, sample_id and source group required")
name, sid, group = (record[k] for k in ("name", "sample_id", "group"))
if name in names or sid in samples:
raise ValueError("Duplicate frame name or sample_id")
names.add(name)
samples.add(sid)
if group not in family_by_group:
raise ValueError("Source group missing from explicit family mapping")
family = family_by_group[group]
if family == held_family:
raise ValueError("Held family must never be admitted; caller must filter it")
observed.add(family)
target = record.get("target")
if (
not isinstance(target, np.ndarray)
or target.dtype != np.uint8
or target.ndim != 2
or not target.size
or not np.isin(target, (0, 1, 255)).all()
):
raise ValueError("Nonempty 2D uint8 targets with labels 0, 1, 255 required")
if not np.any(target != 255):
raise ValueError("Every frame needs known class support")
if observed != set(allowed):
raise ValueError("Every allowed family must be represented in both study arms")
out = [
dict(r, target=r["target"].copy())
for r in sorted(records, key=lambda r: r["sample_id"])
]
weights = {r["name"]: np.zeros(r["target"].shape, dtype=np.float64) for r in out}
support = {
r["name"]: {label: int((r["target"] == label).sum()) for label in (0, 1)}
for r in out
}
family_classes = []
family_mass = 0.5 / len(allowed)
for family in allowed:
rows = [r for r in out if family_by_group[r["group"]] == family]
for label in (0, 1):
present = [r for r in rows if support[r["name"]][label]]
if not present:
raise ValueError("Every allowed family must support both classes")
frame_mass = family_mass / len(present)
for row in present:
mask = row["target"] == label
weights[row["name"]][mask] = frame_mass / support[row["name"]][label]
actual = sum(
float(weights[r["name"]][r["target"] == label].sum()) for r in present
)
if not np.isclose(actual, family_mass, rtol=1e-12, atol=1e-12):
raise ValueError("Family/class mass accounting failed")
family_classes.append(
dict(
family=family,
label=label,
supported_frames=len(present),
pixels=sum(support[r["name"]][label] for r in present),
expected_mass=family_mass,
mass=actual,
)
)
frames = []
for row in out:
target, weight = row["target"], weights[row["name"]]
if (
not np.isfinite(weight).all()
or np.any(weight[target != 255] <= 0)
or np.any(weight[target == 255] != 0)
):
raise ValueError("Finite positive known weights and zero unknown weights required")
frames.append(
dict(
name=row["name"],
sample_id=row["sample_id"],
group=row["group"],
family=family_by_group[row["group"]],
unknown_pixels=int((target == 255).sum()),
mass=float(weight.sum()),
classes=[
dict(
label=label,
pixels=support[row["name"]][label],
mass=float(weight[target == label].sum()),
)
for label in (0, 1)
],
)
)
classes = []
for label in (0, 1):
actual = sum(f["classes"][label]["mass"] for f in frames)
if not np.isclose(actual, 0.5, rtol=1e-12, atol=1e-12):
raise ValueError("Global class mass accounting failed")
classes.append(
dict(
label=label,
expected_mass=0.5,
mass=actual,
pixels=sum(support[r["name"]][label] for r in out),
)
)
total = sum(f["mass"] for f in frames)
if not np.isclose(total, 1.0, rtol=1e-12, atol=1e-12):
raise ValueError("Total mass accounting failed")
return out, weights, dict(
schema="missioncore.diversity-mass/v1",
held_family=held_family,
allowed_families=allowed,
total_mass=total,
classes=classes,
family_classes=family_classes,
frames=frames,
)
def quotas(total_points, frames, step):
"""Allocate positive int64 quotas in frame order; rotate remainder by step.
Sum is total_points; over any complete frames-step cycle every frame receives
exactly total_points draws. The caller aligns this vector with sorted records.
"""
values = (total_points, frames, step)
if any(
not isinstance(v, (int, np.integer)) or isinstance(v, (bool, np.bool_)) for v in values
):
raise ValueError("Integer point budget, frame count and step required")
total_points, frames, step = (int(v) for v in values)
if (
frames <= 0
or total_points < frames
or total_points > np.iinfo(np.int64).max
or step < 0
):
raise ValueError("Positive per-frame budget and nonnegative step required")
base, remainder = divmod(total_points, frames)
result = np.full(frames, base, dtype=np.int64)
start = step % frames
stop = start + remainder
result[start:min(stop, frames)] += 1
result[:max(0, stop - frames)] += 1
return result
@@ -0,0 +1,97 @@
"""Point-wise frozen-scene feature refinement; offline, no location inputs."""
def network(seed, channels=256, width=256):
import torch
from torch import nn
if channels < 1 or width < 1:
raise ValueError("Positive channel counts required")
class Head(nn.Module):
def __init__(self):
super().__init__()
self.layers = nn.ModuleList(
[nn.Linear(channels + 1, width)] + [nn.Linear(width + 1, width) for _ in range(2)]
)
self.output = nn.Linear(width + 1, 1)
for layer in self.layers:
nn.init.kaiming_normal_(layer.weight, nonlinearity="relu")
nn.init.zeros_(layer.bias)
nn.init.zeros_(self.output.weight)
nn.init.zeros_(self.output.bias)
def forward(self, fine, coarse, arm):
if arm not in {"coarse_only", "scene_features"}:
raise ValueError("Unknown feature arm")
if fine.ndim != 2 or coarse.shape != (len(fine), 1):
raise ValueError("Expected points by channels and points by one")
if fine.shape[1] != channels:
raise ValueError("Feature channel mismatch")
x = fine if arm == "scene_features" else torch.zeros_like(fine)
for layer in self.layers:
x = torch.relu(layer(torch.cat((x, coarse), dim=1)))
return coarse + self.output(torch.cat((x, coarse), dim=1))
with torch.random.fork_rng(devices=[]):
torch.manual_seed(seed)
return Head()
def sample_native(fine, shape, indices):
"""Bilinear sample at native pixel centres, align_corners=False, border pad."""
import torch
from torch.nn import functional as F
h, w = shape
if fine.ndim != 4 or fine.shape[0] != 1 or min(h, w) < 1:
raise ValueError("Expected one feature image and positive native shape")
if indices.ndim != 1 or indices.dtype != torch.long:
raise ValueError("Expected flat int64 indices")
if len(indices) and (indices.min() < 0 or indices.max() >= h * w):
raise ValueError("Point outside native image")
y = torch.div(indices, w, rounding_mode="floor").to(fine.dtype)
x = (indices % w).to(fine.dtype)
grid = torch.stack(((x + 0.5) * (2.0 / w) - 1, (y + 0.5) * (2.0 / h) - 1), -1)
return F.grid_sample(
fine, grid[None, None], mode="bilinear", padding_mode="border", align_corners=False
)[0, :, 0].T.contiguous()
def predict(net, fine, coarse, arm, chunk=8192):
import torch
if chunk < 1 or coarse.ndim != 2:
raise ValueError("Expected positive chunk and 2D coarse scores")
out = []
flat = coarse.reshape(-1, 1)
with torch.inference_mode():
for start in range(0, flat.shape[0], chunk):
ids = torch.arange(start, min(start + chunk, len(flat)), device=fine.device)
out.append(net(sample_native(fine, coarse.shape, ids), flat[ids], arm)[:, 0])
return torch.cat(out).reshape(coarse.shape)
def capacity_screen(before, after, control):
"""Frozen TRAIN screen: geometry/error gains without losing known paint."""
import math
required = {"bce", "weak_fn", "clear_fn", "background_fp"}
for row in (before, after, control):
if set(row) != required:
raise ValueError("Incomplete capacity metrics")
if not all(math.isfinite(v) and v >= 0 for v in row.values()):
raise ValueError("Invalid capacity metrics")
if any(type(row[k]) is not int for k in required - {"bce"}):
raise ValueError("Pixel counts must be integers")
checks = {
"half_parent_bce": after["bce"] <= before["bce"] * 0.5,
"half_parent_bg_fp": after["background_fp"] <= before["background_fp"] * 0.5,
"retain_parent_weak": after["weak_fn"] <= before["weak_fn"],
"retain_parent_clear": after["clear_fn"] <= before["clear_fn"],
"beat_control_bce": after["bce"] < control["bce"],
"no_control_bg_regression": after["background_fp"] <= control["background_fp"],
"no_control_weak_regression": after["weak_fn"] <= control["weak_fn"],
"no_control_clear_regression": after["clear_fn"] <= control["clear_fn"],
}
return dict(passed=all(checks.values()), checks=checks, production_eligible=False)
@@ -0,0 +1,120 @@
"""Deterministic review windows over final geometry, independent of mouse history."""
import copy
import math
from dataset_store import digest
from semantic_objects import object_operation, paths
from semantic_vectors import vector_operation
VECTOR = {
"curve",
"delete_vertices",
"region",
"translate",
"translate_vertices",
"duplicate_vertex",
"duplicate_marking",
}
def replay(package):
features = copy.deepcopy(package["model"]["features"])
for row in package["revisions"]:
for op in row["operations"]:
kind = op["kind"]
origin = row.get("origin", "human-edit")
f = next((f for f in features if f["id"] == op.get("feature_id")), None)
if kind in {"place", "transform", "remove", "retemplate"}:
features = object_operation(features, op, origin)
elif (
kind in VECTOR
or f
and f["properties"].get("editor_curves", {}).get(str(op.get("path")))
):
features = vector_operation(features, op, origin)
else:
if not f:
raise ValueError("Unknown feature in annotation history")
points = paths(f)[op["path"]]
i = op["index"]
if kind == "move":
points[i] = op["position"][:]
elif kind == "insert":
a, b = points[i : i + 2]
points.insert(i + 1, [a[k] + op["t"] * (b[k] - a[k]) for k in range(3)])
elif kind == "delete":
points.pop(i)
else:
raise ValueError("Unknown annotation operation")
if f["geometry"]["type"] == "Polygon":
points[-1] = points[0][:]
if {f["id"]: f["geometry"] for f in features} != {
f["id"]: f["geometry"] for f in package["edited"]["features"]
}:
raise ValueError("Replayed geometry differs from admitted edit")
return features
def segment_cells(a, b, step=10):
"""Exact segment/grid intersections: long edges need no inserted label vertices."""
cuts = {0.0, 1.0}
for k in (0, 1):
if a[k] == b[k]:
continue
lo, hi = sorted((a[k], b[k]))
for n in range(math.floor(lo / step) + 1, math.ceil(hi / step)):
cuts.add((n * step - a[k]) / (b[k] - a[k]))
ts = sorted(cuts)
for left, right in zip(ts, ts[1:], strict=False):
t = (left + right) / 2
cell = tuple(math.floor((a[k] + t * (b[k] - a[k])) / step) for k in (0, 1))
yield cell, a[2] + left * (b[2] - a[2])
yield cell, a[2] + right * (b[2] - a[2])
def plan(package, classes=None):
replay(package)
before = package["model"]["features"]
after = package["edited"]["features"]
originals = {f["id"]: f for f in before}
if classes is None:
classes = sorted({f["properties"]["class"] for f in after if originals.get(f["id"]) != f})
if not classes or any(
c not in {f["properties"]["class"] for f in before + after} for c in classes
):
raise ValueError("Unknown/empty review scope")
cells = {}
for _source, features in (("model", before), ("edited", after)):
for f in features:
if f["properties"]["class"] not in classes:
continue
# Rejected geometry remains review evidence, never positive supervision.
for ring in paths(f):
for a, b in zip(ring, ring[1:], strict=False):
for cell, z in segment_cells(a, b):
item = cells.setdefault(cell, {"features": set(), "low": z, "high": z})
item["features"].add(f["id"])
item["low"] = min(z, item["low"])
item["high"] = max(z, item["high"])
windows = [
dict(
id=f"tile-{x}-{y}",
center=[(x + 0.5) * 10, (y + 0.5) * 10, (v["low"] + v["high"]) / 2],
features=sorted(v["features"]),
)
for (x, y), v in sorted(cells.items())
]
if not windows or len(windows) > 1024:
raise ValueError("Review scope exceeds bounded snapshot budget")
return dict(
schema_version="missioncore.semantic-snapshot-plan/v1",
revision=package["revision"],
world_sha256=package["world_sha256"],
classes=sorted(classes),
stride_m=10,
width_m=12,
windows=windows,
geometry_sha256=digest([f for f in after if f["properties"]["class"] in classes]),
training_eligible=False,
)
@@ -0,0 +1,35 @@
"""Predeclared TRAIN-only capacity screen; never a deployment acceptance gate."""
import math
def capacity_screen(before, after):
"""Require halved BCE/weak misses/background errors and no clear-paint loss."""
for row in (before, after):
if set(row) != {"bce", "weak_fn", "background_fp", "clear_fn"}:
raise ValueError("Exact fixed support metrics required")
if (
isinstance(row["bce"], bool)
or not isinstance(row["bce"], (int, float))
or not math.isfinite(row["bce"])
or row["bce"] < 0
):
raise ValueError("Finite nonnegative objective required")
for key in ("weak_fn", "background_fp", "clear_fn"):
if type(row[key]) is not int or row[key] < 0:
raise ValueError("Nonnegative integer error counts required")
limits = {
"bce": before["bce"] * 0.5,
"weak_fn": before["weak_fn"] * 0.5,
"background_fp": before["background_fp"] * 0.5,
"clear_fn": before["clear_fn"],
}
failures = [key for key, limit in limits.items() if after[key] > limit]
return {
"passed": not failures,
"failures": failures,
"limits": limits,
"before": dict(before),
"after": dict(after),
"production_eligible": False,
}
@@ -0,0 +1,101 @@
"""CPU-only representation gate; synthetic contracts, NOT street/model quality."""
import argparse
import json
import time
from pathlib import Path
import numpy as np
from paint_geometry import editor_features, vectorize
from PIL import Image, ImageDraw
from shapely import contains_xy
from shapely.geometry import Polygon, shape
from shapely.ops import unary_union
def fixtures():
dash = np.zeros((64, 96), np.uint8)
for a, b in [(6, 23), (28, 43), (57, 88)]:
dash[29:35, a:b] = 1
zebra = np.zeros_like(dash)
for a in [10, 28, 46, 64, 82]:
zebra[8:56, a:a + 7] = 1
# Raster A is deliberately synthetic, with a small but explicit hole.
yy, xx = np.indices(dash.shape)
outer = Polygon([(20, 56), (43, 7), (53, 7), (77, 56),
(63, 56), (57, 43), (39, 43), (33, 56)])
hole = Polygon([(44, 31), (48, 20), (52, 31)])
letter = contains_xy(outer.difference(hole), xx + .5, yy + .5).astype(np.uint8)
clipped = np.zeros_like(dash)
clipped[27:36, :90] = 1
clipped[:, 43:50] = 255
return {"separate_dashes": dash, "zebra_bars": zebra,
"letter_hole": letter, "unknown_gap_and_edge": clipped}
def rasterize(features, shape_hw, matrix):
yy, xx = np.indices(shape_hw)
a, b, d, e, xoff, yoff = matrix
x, y = a * (xx + .5) + b * (yy + .5) + xoff, d * (xx + .5) + e * (yy + .5) + yoff
return contains_xy(unary_union([shape(f["geometry"]) for f in features]), x, y)
def run(destination):
destination = Path(destination)
destination.mkdir(parents=True, exist_ok=False)
start = time.monotonic()
matrix = [.1, 0, 0, -.1, 10, 20]
report = dict(
scope="Synthetic discrete geometry contract; no model inference or live map",
frame="pixel edges; supplied synthetic height plane only",
upstream_vma_executed=False, production_heuristic_executed=False, cases=[],
)
canvas = Image.new("RGB", (980, 670), "#111820")
draw = ImageDraw.Draw(canvas)
draw.text((16, 12), "SYNTHETIC CONTRACT CHECK - not street predictions", fill="white")
for x, label in [(16, "Input (purple = unknown)"),
(340, "Exact cells -> editor features"),
(664, "Envelope only (lossy illustration)")]:
draw.text((x, 38), label, fill="white")
for index, (name, labels) in enumerate(fixtures().items()):
proposal = vectorize(labels, pixel_to_scene=matrix, source_id="synthetic/" + name)
features = editor_features(
proposal, height_at=lambda xy: 2 + xy[:, 0] * .01,
height_source="synthetic-known-plane",
)
recovered = rasterize(features, labels.shape, matrix)
truth = labels == 1
assert np.array_equal(recovered, truth)
exact = unary_union([shape(f["geometry"]) for f in features])
# Structural illustration only, not an execution/emulation of VMA.
envelope = exact.envelope
simplified = rasterize([dict(geometry=envelope.__geo_interface__)], labels.shape, matrix)
row = dict(
case=name, foreground_pixels=int(truth.sum()), exact_pixel_errors=0,
features=len(features),
holes=sum(len(shape(f["geometry"]).interiors) for f in features),
support_boundary=[f["properties"]["support_boundary"] for f in features],
envelope_pixel_errors=int(np.count_nonzero(simplified != truth)),
proposal_sha256=proposal["proposal_sha256"],
)
report["cases"].append(row)
y = 66 + index * 146
draw.text((16, y), name, fill="white")
for x, mask in [(16, truth), (340, recovered), (664, simplified)]:
rgb = np.zeros((*labels.shape, 3), np.uint8)
rgb[:] = [28, 38, 49]
rgb[mask] = [246, 215, 100]
if x == 16:
rgb[labels == 255] = [136, 91, 185]
# 96x64 to 288x112 display; dimensions are shared across columns.
im = Image.fromarray(rgb).resize((288, 112), Image.Resampling.NEAREST)
canvas.paste(im, (x, y + 18))
report["seconds"] = time.monotonic() - start
(destination / "gate.json").write_text(json.dumps(report, indent=2) + "\n")
canvas.save(destination / "geometry-proof.png")
return report
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("destination", type=Path)
print(json.dumps(run(parser.parse_args().destination), indent=2))
@@ -0,0 +1,238 @@
"""Offline street-grouped threshold experiment; no publication or map writes."""
import json
import sys
from collections import defaultdict
from pathlib import Path
import numpy as np
from object_assembly_study import measured
from object_proposal_study import aggregate, labels, save_new, sha, timestamp
from paint_hypothesis_study import fit_classifier, probability
def development(records, streets):
"""Explicit allowlist prevents previous controls entering a development fold."""
return [r for r in records if r["street"] in streets]
def fit(records, review):
x, y = [], []
for r in records:
cs = r["variants"]["retained_off"]
for c, label in zip(cs, labels(cs, review[r["id"]]), strict=True):
if label >= 0:
x.append(c["features"][:14])
y.append(int(label))
if min(y.count(0), y.count(1)) < 2:
raise ValueError("Insufficient positive or negative development examples")
return fit_classifier(np.asarray(x), np.asarray(y), 0.01, 500)
def probabilities(records, model):
return {
r["id"]: probability(
np.asarray([c["features"][:14] for c in r["variants"]["retained_off"]]), model
).tolist()
if r["variants"]["retained_off"]
else []
for r in records
}
def evaluated(records, review, probs, threshold):
rows = []
for r in records:
accepted = [
c
for c, p in zip(r["variants"]["retained_off"], probs[r["id"]], strict=True)
if p >= threshold
]
rows.append(
dict(
id=r["id"],
street=r["street"],
accepted_ids=[c["id"] for c in accepted],
**measured(accepted, review[r["id"]]),
)
)
return dict(
rows=rows,
summary=aggregate(rows),
streets={
st: aggregate([a for a in rows if a["street"] == st])
for st in sorted({r["street"] for r in rows})
},
)
def objective(rows, ceiling):
"""Score recall of complete matchable objects, balancing streets and families."""
streets, families = defaultdict(lambda: [0, 0]), defaultdict(lambda: [0, 0])
for r in rows:
eligible = {o["id"] for o in ceiling[r["id"]]["objects"] if o["matched"]}
for obj in r["objects"]:
if obj["id"] in eligible:
for group, key in [(streets, r["street"]), (families, obj["family"])]:
group[key][0] += int(obj["matched"])
group[key][1] += 1
return dict(
worst_street=min((n / d for n, d in streets.values()), default=0),
macro_family=float(np.mean([n / d for n, d in families.values()])) if families else 0,
street_matchable=dict(streets),
family_matchable=dict(families),
)
def select(rows):
feasible = [r for r in rows if r["unsupported"] == 0]
if not feasible:
return None
def key(r):
return r["worst_street"], r["macro_family"], r["found"]
best = max(key(r) for r in feasible)
tied = sorted([r for r in feasible if key(r) == best], key=lambda r: r["threshold"])
return tied[(len(tied) - 1) // 2]
def transfer_gate(baseline, candidate):
lost = []
by_id = {r["id"]: r for r in candidate["rows"]}
for row in baseline["rows"]:
found = {o["id"] for o in by_id[row["id"]]["objects"] if o["matched"]}
lost.extend(o["id"] for o in row["objects"] if o["matched"] and o["id"] not in found)
no_extra_fp = all(
candidate["streets"][st]["unsupported"] <= b["unsupported"]
for st, b in baseline["streets"].items()
)
b, c = baseline["summary"], candidate["summary"]
gain = c["found"] > b["found"] or c["unsupported"] < b["unsupported"]
return dict(
lost_objects=lost,
no_extra_reviewed_fp=no_extra_fp,
strict_gain=gain,
passed=not lost and no_extra_fp and gain,
)
def train(root):
protocol = json.loads((root / "protocol.json").read_text())
source = Path("/assemblystudy")
records = development(
json.loads((source / "assembled-candidates.json").read_text())["records"],
protocol["development_streets"],
)
review = json.loads((source / "review-frozen.json").read_text())["records"]
folds, out = {}, {}
for street in sorted({r["street"] for r in records}):
training = [r for r in records if r["street"] != street]
validation = [r for r in records if r["street"] == street]
model = fit(training, review)
out.update(probabilities(validation, model))
folds[street] = dict(
training_streets=sorted({r["street"] for r in training}),
validation_ids=[r["id"] for r in validation],
model=model,
)
ceiling = {r["id"]: measured(r["variants"]["retained_off"], review[r["id"]]) for r in records}
sweep = []
for t in protocol["thresholds"]:
result = evaluated(records, review, out, t)
sweep.append(
dict(
threshold=t,
**result["summary"],
**objective(result["rows"], ceiling),
merged=sum(r["merged"] for r in result["rows"]),
)
)
chosen = select(sweep)
save_new(
root / "models-frozen.json",
dict(
**timestamp(),
protocol_sha256=sha(root / "protocol.json"),
source_sha256=sha(Path(__file__)),
input_sha256={
str(source / n): sha(source / n)
for n in ["assembled-candidates.json", "review-frozen.json"]
},
selected=chosen,
sweep=sweep,
folds=folds,
out_of_fold=out,
final_model=fit(records, review),
),
)
print(json.dumps(dict(selected=chosen, folds=len(folds), windows=len(records))))
def evaluate(root):
frozen = json.loads((root / "models-frozen.json").read_text())
if frozen["selected"] is None:
raise ValueError("No feasible out-of-fold threshold; hypothesis rejected")
assert frozen["protocol_sha256"] == sha(root / "protocol.json")
assert frozen["source_sha256"] == sha(Path(__file__))
for path, digest in frozen["input_sha256"].items():
assert sha(Path(path)) == digest
old = json.loads(Path("/objectstudy/models-frozen.json").read_text())["models"][
"shape_appearance"
]
results = {}
for cohort in ["known_regression", "fresh_control"]:
if cohort == "known_regression":
records = [
r
for r in json.loads(Path("/assemblystudy/assembled-candidates.json").read_text())[
"records"
]
if r["street"] in ["pokrovka", "sadovaya-karetnaya"]
]
review = json.loads(Path("/assemblystudy/review-frozen.json").read_text())["records"]
else:
records = json.loads((root / "candidates.json").read_text())["records"]
records = [
dict(r, variants={"retained_off": r["variants"]["retained"]}) for r in records
]
review = json.loads((root / "review-frozen.json").read_text())["records"]
base = evaluated(records, review, probabilities(records, old["model"]), 0.15)
new = evaluated(
records,
review,
probabilities(records, frozen["final_model"]),
frozen["selected"]["threshold"],
)
ceiling = evaluated(
records,
review,
{r["id"]: [1.0] * len(r["variants"]["retained_off"]) for r in records},
0.0,
)
results[cohort] = dict(
baseline=base, grouped=new, proposal_ceiling=ceiling, gate=transfer_gate(base, new)
)
save_new(
root / "results.json",
dict(
**timestamp(),
frozen_sha256=sha(root / "models-frozen.json"),
fresh_inputs={
n: sha(root / n) for n in ["inputs.json", "review-frozen.json", "candidates.json"]
},
cohorts=results,
),
)
print(
json.dumps(
{
k: {n: v[n]["summary"] for n in ["baseline", "grouped", "proposal_ceiling"]}
| {"gate": v["gate"]}
for k, v in results.items()
}
)
)
if __name__ == "__main__":
{"train": train, "evaluate": evaluate}[sys.argv[1]](Path(sys.argv[2]))
+28
View File
@@ -0,0 +1,28 @@
param([Parameter(Mandatory=$true)][string]$Release,[switch]$Apply)
$ErrorActionPreference='Stop'
$root='D:\NDC_MISSIONCORE\datasets\urban-learning'
$runtime='D:\NDC_MISSIONCORE\runtime\simulation'
$python="$runtime\isaac-sim-6.1.0\kit\python\python.exe"
$manifest=Get-Content "$Release\release.json" -Raw | ConvertFrom-Json
foreach($f in $manifest.files.psobject.Properties){
$path=Join-Path $Release $f.Name
if((Get-FileHash $path -Algorithm SHA256).Hash.ToLower() -ne $f.Value){throw "Release identity mismatch: $($f.Name)"}
}
if(-not (Test-Path $python)){throw 'Worker Python unavailable'}
$image=& docker image inspect $manifest.image --format '{{.Id}}'
if($LASTEXITCODE -ne 0 -or $image -ne $manifest.image){throw 'Pinned renderer unavailable'}
$arguments="-B -u `"$Release\worker.py`" --root `"$root`" --state `"$runtime\state`" --token-file `"$runtime\private\worker.token`""
if(-not $Apply){Write-Output $arguments;exit}
New-Item -ItemType Directory -Force -Path $root | Out-Null
$old=Get-ScheduledTask -TaskName 'ndc-semantic-learning-worker' -ErrorAction SilentlyContinue
if($old){
if($old.State -eq 'Running'){throw 'Stop the owned learning worker only after checking its active job'}
Export-ScheduledTask -TaskName 'ndc-semantic-learning-worker' | Set-Content "$root\previous-task.xml"
}
$action=New-ScheduledTaskAction -Execute $python -Argument $arguments -WorkingDirectory $Release
$principal=New-ScheduledTaskPrincipal -UserId ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name) -LogonType Interactive -RunLevel Limited
$trigger=New-ScheduledTaskTrigger -AtLogOn -User $principal.UserId
$settings=New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1) -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
Register-ScheduledTask -TaskName 'ndc-semantic-learning-worker' -Action $action -Principal $principal -Trigger $trigger -Settings $settings -Force | Out-Null
Start-ScheduledTask -TaskName 'ndc-semantic-learning-worker'
Write-Output 'Installed ndc-semantic-learning-worker; data root is separate from runtime and release'
@@ -0,0 +1,16 @@
"""Extend reviewed labels without silently overriding known or locked unknown."""
import numpy as np
def extend_reviewed_target(base, proposal, protected):
if (not isinstance(base, np.ndarray) or base.ndim != 2 or base.dtype != np.uint8
or not isinstance(proposal, np.ndarray) or proposal.shape != base.shape
or proposal.dtype != np.uint8 or not isinstance(protected, np.ndarray)
or protected.shape != base.shape or protected.dtype != np.bool_
or not np.isin(base, [0, 1, 255]).all()
or not np.isin(proposal, [0, 1, 255]).all()):
raise ValueError("Aligned uint8 labels and explicit bool protection required")
preserve = protected | (base != 255)
result = proposal.copy()
result[preserve] = base[preserve]
return result
@@ -0,0 +1,465 @@
"""Pinned, resumable phase ledger for trusted offline learning runners.
This is not a scheduler, an authentication boundary or a model acceptance gate.
The input root may be a read-only portable store with a separate writable
state_root for this run's ledger. Plans declare the actual file dependency closure;
metadata references are not recursively inferred. The caller supplies the bounded
Worker/container runtime and whole-phase wall
budget. Run and verification subprocesses have separate explicit deadlines. A completed phase is
reused only while its input and output bytes still match. Any interrupted or
failed attempt reserves its phase until trusted root reconciliation; time alone
never authorizes a retry. Verifiers validate artifacts, not model quality.
"""
import argparse
import json
import re
import sqlite3
import subprocess
import sys
import threading
import time
import uuid
from contextlib import contextmanager
from pathlib import Path
from dataset_store import checksum, confined, digest
SCHEMA = "missioncore.learning-execution/v1"
MAX_JSON = 262144
MAX_LOG = 1048576
def encoded(value):
data = json.dumps(value, sort_keys=True, ensure_ascii=True, allow_nan=False)
if len(data.encode()) > MAX_JSON:
raise ValueError("Execution record too large")
return data
def pin(root, name):
path = confined(root, name)
if not path.is_file():
raise ValueError("Missing regular artifact: " + name)
return dict(sha256=checksum(path), bytes=path.stat().st_size)
def check_pins(root, pins):
for name, expected in pins.items():
if pin(root, name) != expected:
raise ValueError("Artifact changed: " + name)
def invoke(root, argv, timeout):
"""No shell; deadline and in-memory output cap, no unbounded log file."""
process = subprocess.Popen(
[sys.executable, "-B", str(confined(root, argv[0])), *argv[1:]],
cwd=root,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
output = bytearray()
overflow = threading.Event()
def collect():
while chunk := process.stdout.read(65536):
if len(output) + len(chunk) > MAX_LOG:
overflow.set()
process.kill()
return
output.extend(chunk)
reader = threading.Thread(target=collect, daemon=True)
reader.start()
try:
process.wait(timeout=timeout)
except BaseException:
process.kill()
process.wait(timeout=5)
raise
finally:
reader.join(timeout=2)
if not reader.is_alive():
process.stdout.close()
if reader.is_alive():
raise ValueError("Runner left an unconfirmed output producer")
if overflow.is_set():
raise ValueError("Runner diagnostic output exceeded limit")
text = output.decode("utf-8", errors="strict")
if process.returncode:
raise ValueError(f"Runner returned {process.returncode}: {text[-4000:]}")
return text
class Execution:
def __init__(self, root, *, state_root=None, clock=time.time, runner=invoke):
self.root = Path(root).resolve()
if state_root is None:
self.root.mkdir(parents=True, exist_ok=True)
self.state_root = self.root
else:
if not self.root.is_dir():
raise ValueError("Pinned input root must already exist")
self.state_root = Path(state_root).resolve()
self.state_root.mkdir(parents=True, exist_ok=True)
self.clock, self.runner = clock, runner
self.db = sqlite3.connect(self.state_root / "learning-execution.sqlite3", timeout=10)
self.db.row_factory = sqlite3.Row
self.db.execute("PRAGMA synchronous=FULL")
self.db.executescript("""
CREATE TABLE IF NOT EXISTS learning_runs (
id TEXT PRIMARY KEY, plan TEXT NOT NULL, created REAL NOT NULL);
CREATE TABLE IF NOT EXISTS learning_phases (
run TEXT NOT NULL, position INTEGER NOT NULL, name TEXT NOT NULL,
state TEXT NOT NULL, token TEXT, started REAL, finished REAL,
receipt TEXT, incident TEXT, reconciliation TEXT,
PRIMARY KEY(run,name));
""")
def close(self):
self.db.close()
@contextmanager
def transaction(self):
self.db.execute("BEGIN IMMEDIATE")
try:
yield
self.db.commit()
except BaseException:
self.db.rollback()
raise
def register(self, plan):
raw = encoded(plan)
if set(plan) != {"schema", "objective", "inputs", "phases"} or plan["schema"] != SCHEMA:
raise ValueError("Unsupported execution plan")
if not isinstance(plan["objective"], str) or not 1 <= len(plan["objective"]) <= 4096:
raise ValueError("Objective required")
if not isinstance(plan["inputs"], dict) or not 1 <= len(plan["inputs"]) <= 1024:
raise ValueError("Bounded pinned inputs required")
for name, value in plan["inputs"].items():
if (
set(value) != {"sha256", "bytes"}
or not re.fullmatch(r"[0-9a-f]{64}", value["sha256"])
or type(value["bytes"]) is not int
or value["bytes"] < 0
):
raise ValueError("Exact input pin required")
confined(self.root, name)
phases = plan["phases"]
if not isinstance(phases, list) or not 1 <= len(phases) <= 12:
raise ValueError("One to twelve phases required")
names, outputs = set(), set()
for phase in phases:
if set(phase) != {
"name",
"run",
"verify",
"outputs",
"run_timeout_seconds",
"verify_timeout_seconds",
}:
raise ValueError("Exact phase contract required")
name = phase["name"]
if (
not isinstance(name, str)
or not re.fullmatch(r"[a-z][a-z0-9_-]{0,47}", name)
or name in names
):
raise ValueError("Unique phase name required")
names.add(name)
for action in ("run", "verify"):
argv = phase[action]
if (
not isinstance(argv, list)
or not 1 <= len(argv) <= 16
or any(not isinstance(x, str) or len(x) > 4096 or "\x00" in x for x in argv)
or argv[0] not in plan["inputs"]
or not argv[0].endswith(".py")
):
raise ValueError("Pinned Python command required")
members = phase["outputs"]
if not isinstance(members, list) or not 1 <= len(members) <= 32:
raise ValueError("Declared phase outputs required")
for member in members:
confined(self.root, member)
if member in outputs or member in plan["inputs"]:
raise ValueError("Output aliases another output or input")
outputs.add(member)
for field, limit in (("run_timeout_seconds", 7200), ("verify_timeout_seconds", 300)):
if type(phase[field]) is not int or not 1 <= phase[field] <= limit:
raise ValueError("Bounded per-process deadline required")
check_pins(self.root, plan["inputs"])
identity = digest(plan)
with self.transaction():
if self.db.execute("SELECT 1 FROM learning_runs WHERE id=?", (identity,)).fetchone():
return identity
if self.db.execute(
"SELECT 1 FROM learning_phases WHERE state IN ('running','unknown')"
).fetchone():
raise ValueError("An unfinished executor still owns resources")
total = self.db.execute(
"SELECT COALESCE(SUM(length(CAST(plan AS BLOB))),0) FROM learning_runs"
).fetchone()[0]
count = self.db.execute("SELECT COUNT(*) FROM learning_runs").fetchone()[0]
if total + len(raw.encode()) > 16 * 1024**2 or count >= 512:
raise ValueError("Execution ledger quota reached; archive closed runs")
for name in outputs:
if confined(self.root, name).exists():
raise ValueError("Unowned output already exists: " + name)
self.db.execute(
"INSERT INTO learning_runs VALUES(?,?,?)", (identity, raw, self.clock())
)
self.db.executemany(
"INSERT INTO learning_phases(run,position,name,state) VALUES(?,?,?,'pending')",
[(identity, i, p["name"]) for i, p in enumerate(phases)],
)
return identity
def status(self, identity):
run = self.db.execute("SELECT * FROM learning_runs WHERE id=?", (identity,)).fetchone()
if run is None:
raise ValueError("Unknown execution")
phases = []
for row in self.db.execute(
"SELECT * FROM learning_phases WHERE run=? ORDER BY position", (identity,)
):
receipt = json.loads(row["receipt"]) if row["receipt"] else None
phases.append(
dict(
name=row["name"],
state=row["state"],
token=row["token"],
started=row["started"],
finished=row["finished"],
receipt_sha256=digest(receipt) if receipt else None,
output_count=len(receipt["outputs"]) if receipt else 0,
artifact_count=len(receipt["artifacts"]) if receipt else 0,
incident=row["incident"],
reconciled=row["reconciliation"] is not None,
)
)
return dict(id=identity, phases=phases)
def _context(self, identity, name):
row = self.db.execute("SELECT plan FROM learning_runs WHERE id=?", (identity,)).fetchone()
if row is None:
raise ValueError("Unknown execution")
plan = json.loads(row["plan"])
phase = next((p for p in plan["phases"] if p["name"] == name), None)
if phase is None:
raise ValueError("Unknown phase")
previous_artifacts = {}
for previous in plan["phases"]:
if previous["name"] == name:
break
row = self.db.execute(
"SELECT state,receipt FROM learning_phases WHERE run=? AND name=?",
(identity, previous["name"]),
).fetchone()
if row["state"] != "complete":
raise ValueError("Previous phase is not complete")
for member, expected in json.loads(row["receipt"])["artifacts"].items():
if member in previous_artifacts and previous_artifacts[member] != expected:
raise ValueError("Conflicting previous artifact pins: " + member)
previous_artifacts[member] = expected
# Merge only within this boundary. Every later pre/post/resume call hashes again.
# Validate conflicts before reading payloads; never let a later receipt replace a pin.
check_pins(self.root, plan["inputs"])
check_pins(self.root, previous_artifacts)
return plan, phase
def _verify(self, identity, phase, token):
before = {name: pin(self.root, name) for name in phase["outputs"]}
raw = self.runner(self.root, phase["verify"], phase["verify_timeout_seconds"])
if len(raw.encode()) > MAX_JSON:
raise ValueError("Verifier receipt too large")
verdict = json.loads(raw)
if (
set(verdict) != {"valid", "outputs", "artifacts"}
or verdict["valid"] is not True
or verdict["outputs"] != before
):
raise ValueError("Verifier did not validate exact declared outputs")
artifacts = verdict["artifacts"]
if (
not isinstance(artifacts, dict)
or not 1 <= len(artifacts) <= 1024
or any(artifacts.get(name) != expected for name, expected in before.items())
):
raise ValueError("Verifier artifact closure must contain exact declared outputs")
for expected in artifacts.values():
if (
not isinstance(expected, dict)
or set(expected) != {"sha256", "bytes"}
or not isinstance(expected["sha256"], str)
or not re.fullmatch(r"[0-9a-f]{64}", expected["sha256"])
or type(expected["bytes"]) is not int
or expected["bytes"] < 0
):
raise ValueError("Exact artifact closure pins required")
check_pins(self.root, artifacts)
self._context(identity, phase["name"])
return dict(
schema=SCHEMA,
run=identity,
phase=phase["name"],
token=token,
outputs=before,
artifacts=artifacts,
artifact_validation=True,
model_acceptance=False,
)
def execute(self, identity, name):
with self.transaction():
_, phase = self._context(identity, name)
row = self.db.execute(
"SELECT * FROM learning_phases WHERE run=? AND name=?", (identity, name)
).fetchone()
if row["state"] == "complete":
receipt = json.loads(row["receipt"])
check_pins(self.root, receipt["artifacts"])
return receipt
if (
row["state"] != "pending"
or self.db.execute(
"SELECT 1 FROM learning_phases WHERE state IN ('running','unknown')"
).fetchone()
):
raise ValueError("Unfinished executor requires root reconciliation")
if any(confined(self.root, x).exists() for x in phase["outputs"]):
raise ValueError("Unowned phase output exists")
used = self.db.execute(
"SELECT COALESCE(SUM(COALESCE(length(CAST(receipt AS BLOB)),0) + "
"COALESCE(length(CAST(reconciliation AS BLOB)),0)),0) FROM learning_phases"
).fetchone()[0]
if used + MAX_JSON + 8192 > 32 * 1024**2:
raise ValueError("Execution receipt quota reached; archive closed runs")
token = uuid.uuid4().hex
self.db.execute(
"UPDATE learning_phases SET state='running',token=?,started=? "
"WHERE run=? AND name=?",
(token, self.clock(), identity, name),
)
try:
self.runner(self.root, phase["run"], phase["run_timeout_seconds"])
receipt = self._verify(identity, phase, token)
with self.transaction():
self._finish(identity, name, token, receipt)
return receipt
except BaseException as error:
with self.transaction():
self.db.execute(
"UPDATE learning_phases SET state='unknown',incident=? "
"WHERE run=? AND name=? AND token=? AND state='running'",
(str(error)[:4096], identity, name, token),
)
raise
def _finish(self, identity, name, token, receipt):
changed = self.db.execute(
"UPDATE learning_phases SET state='complete',receipt=?,finished=? "
"WHERE run=? AND name=? AND token=? AND state IN ('running','unknown')",
(encoded(receipt), self.clock(), identity, name, token),
).rowcount
if changed != 1:
raise ValueError("Executor token is stale")
def reconcile(self, identity, name, token, stopped_evidence):
"""Trusted root attests process termination. Never launches/retries fit.
A lost acknowledgement can be recovered only by the same pinned verifier.
Incomplete/invalid outputs retain ownership; caller must archive and close
the failed experiment explicitly, rather than rerun into partial output.
"""
if not isinstance(stopped_evidence, str) or not 1 <= len(stopped_evidence) <= 4096:
raise ValueError("Root termination evidence required")
_, phase = self._context(identity, name)
row = self.db.execute(
"SELECT * FROM learning_phases WHERE run=? AND name=?", (identity, name)
).fetchone()
if row["state"] not in ("running", "unknown") or row["token"] != token:
raise ValueError("No matching unfinished executor")
receipt = self._verify(identity, phase, token)
with self.transaction():
self._finish(identity, name, token, receipt)
self.db.execute(
"UPDATE learning_phases SET reconciliation=? WHERE run=? AND name=?",
(stopped_evidence, identity, name),
)
return receipt
def close_failed(self, identity, name, token, stopped_evidence, archive):
"""Trusted root closes a stopped, archived failure; outputs are preserved."""
if not isinstance(stopped_evidence, str) or not 1 <= len(stopped_evidence) <= 4096:
raise ValueError("Root termination evidence required")
if not isinstance(archive, dict) or len(archive) != 1:
raise ValueError("One verified failure archive required")
check_pins(self.root, archive)
with self.transaction():
row = self.db.execute(
"SELECT * FROM learning_phases WHERE run=? AND name=?", (identity, name)
).fetchone()
if row is None or row["state"] not in ("running", "unknown") or row["token"] != token:
raise ValueError("No matching unfinished executor")
receipt = dict(
stopped_evidence=stopped_evidence,
archive=archive,
outputs_preserved=True,
retry_authorized=False,
)
self.db.execute(
"UPDATE learning_phases SET state='failed',finished=?,reconciliation=? "
"WHERE run=? AND name=?",
(self.clock(), encoded(receipt), identity, name),
)
return receipt
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("root", type=Path)
parser.add_argument("--state-root", type=Path)
sub = parser.add_subparsers(dest="action", required=True)
register = sub.add_parser("register")
register.add_argument("manifest", type=Path)
for action in ("status", "execute", "reconcile", "close-failed"):
command = sub.add_parser(action)
command.add_argument("identity")
if action != "status":
command.add_argument("phase")
if action in ("reconcile", "close-failed"):
command.add_argument("token")
command.add_argument("stopped_evidence")
if action == "close-failed":
command.add_argument("archive")
args = parser.parse_args()
run = Execution(args.root, state_root=args.state_root)
try:
if args.action == "register":
data = args.manifest.read_bytes()
if len(data) > MAX_JSON:
raise ValueError("Manifest too large")
result = run.register(json.loads(data))
elif args.action == "status":
result = run.status(args.identity)
elif args.action == "execute":
result = run.execute(args.identity, args.phase)
elif args.action == "reconcile":
result = run.reconcile(args.identity, args.phase, args.token, args.stopped_evidence)
else:
result = run.close_failed(
args.identity,
args.phase,
args.token,
args.stopped_evidence,
{args.archive: pin(run.root, args.archive)},
)
print(encoded(result))
finally:
run.close()
if __name__ == "__main__":
main()
@@ -0,0 +1,241 @@
"""Bounded linear capacity/optimizer control over frozen features, offline only.
This changes both capacity and optimizer relative to the MLP control; it does not
isolate either cause or qualify transfer. Inputs contain only known binary labels.
Timeouts are cooperative between tensor operations; an external process deadline
must bound a stalled kernel. No torch import or fitting occurs at module import.
"""
import math
import time
L2 = 0.01
MAX_ITER = 300
MAX_EVAL = 400
TOLERANCE_GRAD = 1e-5
TOLERANCE_CHANGE = 1e-10
STATIONARITY_LIMIT = 1e-4
FIT_TIMEOUT_SECONDS = 120.0
EVALUATION_TIMEOUT_SECONDS = 120.0
ARMS = frozenset({"coarse_only", "scene_features"})
def network(seed=0, channels=256):
"""Return a zero-initialized head compatible with feature_refinement.predict.
``seed`` is accepted for the existing factory interface but cannot affect the
zero initialization. Creating this head does not consume the torch RNG.
"""
import torch
from torch import nn
if type(channels) is not int or channels < 1:
raise ValueError("Positive integer feature channel count required")
class Head(nn.Module):
def __init__(self):
super().__init__()
self.weight = nn.Parameter(torch.zeros(1, channels + 1))
self.bias = nn.Parameter(torch.zeros(1))
def forward(self, fine, coarse, arm):
if arm not in ARMS:
raise ValueError("Unknown feature arm")
if fine.ndim != 2 or fine.shape[1] != channels:
raise ValueError("Expected points by feature channels")
if coarse.shape != (len(fine), 1):
raise ValueError("Expected points by one coarse logits")
for value in (fine, coarse):
if value.dtype != self.weight.dtype or value.device != self.weight.device:
raise ValueError("Head and features must have the same dtype and device")
x = fine if arm == "scene_features" else torch.zeros_like(fine)
return coarse + nn.functional.linear(
torch.cat((x, coarse), dim=1), self.weight, self.bias
)
return Head()
def _validate(Xfine, coarse, target, weights, arm, chunk):
import torch
if arm not in ARMS:
raise ValueError("Unknown feature arm")
if type(chunk) is not int or chunk < 1:
raise ValueError("Positive integer chunk required")
values = (Xfine, coarse, target, weights)
if not all(isinstance(value, torch.Tensor) for value in values):
raise ValueError("All inputs must be torch tensors")
if Xfine.ndim != 2 or min(Xfine.shape) < 1:
raise ValueError("Expected nonempty points by feature channels")
n = len(Xfine)
if coarse.shape != (n, 1):
raise ValueError("Expected points by one coarse logits")
if target.shape not in {(n,), (n, 1)} or weights.shape not in {(n,), (n, 1)}:
raise ValueError("Expected one target and weight per point")
if Xfine.dtype not in {torch.float32, torch.float64}:
raise ValueError("Features must be float32 or float64")
if coarse.dtype != Xfine.dtype or weights.dtype != Xfine.dtype:
raise ValueError("Features, coarse logits and weights must share a floating dtype")
if target.is_complex() or target.dtype not in {
torch.bool, torch.uint8, torch.int8, torch.int16, torch.int32,
torch.int64, torch.float32, torch.float64,
}:
raise ValueError("Targets must have a real binary dtype")
if any(value.device != Xfine.device for value in values):
raise ValueError("All inputs must share a device")
if any(value.requires_grad for value in values):
raise ValueError("Inputs must be frozen, without input gradients")
if not all(bool(torch.isfinite(value).all()) for value in values):
raise ValueError("Inputs must be finite")
if not bool(((target == 0) | (target == 1)).all()):
raise ValueError("Only binary known targets 0/1 allowed, including at zero weight")
if not bool((weights >= 0).all()):
raise ValueError("Weights must be nonnegative")
weight_sum = weights.sum(dtype=torch.float64)
if not bool(torch.isfinite(weight_sum)) or float(weight_sum) <= 0:
raise ValueError("Weights must have a finite positive sum")
return target.reshape(-1, 1).to(Xfine.dtype), weights.reshape(-1, 1) / weight_sum
class _TechnicalStop(RuntimeError):
pass
def fit(Xfine, coarse, target, weights, arm="scene_features", *, chunk=8192):
"""Fit all supplied known pixels and return ``(head, diagnostics)``.
Objective: sum(w * BCE) / sum(w) + .5 * .01 * sum(residual_params**2).
Bias and inactive fine coefficients are penalized as well, making the finite
dimensional objective strongly convex. Weight scale and pixel duplication do
not alter its definition. Chunking bounds activation memory, not sample count.
All hyperparameters are frozen constants. At most 400 objective/gradient
evaluations include a reserved final evaluation at the optimizer's returned
parameters. A technical stop returns the last fully evaluated parameters, if
any, and cannot be interpreted as a negative learning result.
"""
import torch
from torch.nn import functional as F
started = time.monotonic()
y, normalized_weights = _validate(Xfine, coarse, target, weights, arm, chunk)
head = network(channels=Xfine.shape[1]).to(Xfine)
parameters = list(head.parameters())
optimizer = torch.optim.LBFGS(
parameters, lr=1.0, max_iter=MAX_ITER, max_eval=MAX_EVAL,
tolerance_grad=TOLERANCE_GRAD, tolerance_change=TOLERANCE_CHANGE,
history_size=100, line_search_fn="strong_wolfe",
)
evaluations = 0
completed_evaluations = 0
last_values = None
last_parameters = [p.detach().clone() for p in parameters]
stop_reason = None
runtime_error = None
def check_time(evaluation_started):
now = time.monotonic()
if now - started >= FIT_TIMEOUT_SECONDS:
raise _TechnicalStop("fit_timeout")
if now - evaluation_started >= EVALUATION_TIMEOUT_SECONDS:
raise _TechnicalStop("evaluation_timeout")
def evaluate(*, final=False):
nonlocal evaluations, completed_evaluations, last_values, last_parameters
# LBFGS line searches can otherwise exceed the nominal max_eval budget.
if evaluations >= MAX_EVAL - (0 if final else 1):
raise _TechnicalStop("evaluation_limit")
evaluation_started = time.monotonic()
check_time(evaluation_started)
evaluations += 1
optimizer.zero_grad(set_to_none=True)
data_loss = Xfine.new_zeros(())
for start in range(0, len(Xfine), chunk):
check_time(evaluation_started)
end = min(start + chunk, len(Xfine))
logits = head(Xfine[start:end], coarse[start:end], arm)
term = (
F.binary_cross_entropy_with_logits(logits, y[start:end], reduction="none")
* normalized_weights[start:end]
).sum()
if not bool(torch.isfinite(term)):
raise _TechnicalStop("nonfinite_objective")
term.backward()
data_loss += term.detach()
check_time(evaluation_started)
l2_loss = 0.5 * L2 * sum(p.square().sum() for p in parameters)
if not bool(torch.isfinite(l2_loss)):
raise _TechnicalStop("nonfinite_objective")
l2_loss.backward()
gradients = torch.cat([p.grad.reshape(-1) for p in parameters])
if not bool(torch.isfinite(gradients).all()):
raise _TechnicalStop("nonfinite_gradient")
objective = data_loss + l2_loss.detach()
if not bool(torch.isfinite(objective)):
raise _TechnicalStop("nonfinite_objective")
values = {
"loss": float(objective), "data_loss": float(data_loss),
"l2_loss": float(l2_loss.detach()),
"gradient_inf_norm": float(gradients.abs().max()),
}
check_time(evaluation_started)
last_values = values
last_parameters = [p.detach().clone() for p in parameters]
completed_evaluations += 1
return objective
try:
optimizer.step(evaluate)
evaluate(final=True)
except _TechnicalStop as exc:
stop_reason = str(exc)
except RuntimeError as exc:
stop_reason = "optimizer_runtime_error"
runtime_error = str(exc)
if stop_reason is not None:
with torch.no_grad():
for parameter, saved in zip(parameters, last_parameters, strict=True):
parameter.copy_(saved)
values = last_values or dict(
loss=None, data_loss=None, l2_loss=None, gradient_inf_norm=None,
)
stationarity = (
values["gradient_inf_norm"] is not None
and math.isfinite(values["gradient_inf_norm"])
and values["gradient_inf_norm"] <= STATIONARITY_LIMIT
)
if stop_reason is None and not stationarity:
stop_reason = "stationarity_not_met"
# A timeout remains a technical stop even if the last iterate was stationary.
converged = stop_reason is None and stationarity
head.zero_grad(set_to_none=True)
head.eval()
diagnostics = {
"status": "converged" if converged else "technical_stop",
"converged": converged, "stop_reason": stop_reason,
**values,
"stationarity": {"passed": stationarity, "limit": STATIONARITY_LIMIT},
"arm": arm, "points": len(Xfine),
"parameter_count": sum(p.numel() for p in parameters),
"parameters": {
"weight": head.weight.detach().cpu().tolist(),
"bias": head.bias.detach().cpu().tolist(),
},
"evaluations": evaluations, "completed_evaluations": completed_evaluations,
"iterations": optimizer.state.get(parameters[0], {}).get("n_iter", 0),
"seconds": time.monotonic() - started,
"configuration": {
"l2": L2, "max_iter": MAX_ITER, "max_eval": MAX_EVAL,
"tolerance_grad": TOLERANCE_GRAD, "tolerance_change": TOLERANCE_CHANGE,
"line_search_fn": "strong_wolfe", "chunk": chunk,
"fit_timeout_seconds": FIT_TIMEOUT_SECONDS,
"evaluation_timeout_seconds": EVALUATION_TIMEOUT_SECONDS,
},
"limitation": "Capacity and optimizer both differ from the MLP control.",
"production_eligible": False,
}
if runtime_error is not None:
diagnostics["runtime_error"] = runtime_error
return head, diagnostics
@@ -0,0 +1,219 @@
"""Validated mixed TRAIN labels with conserved physical-group class masses.
Inputs come from hash-verified ``Supervision.training_batches('observed_paint')``.
This adapter does not admit reviews or authenticate their author. The caller pins
an independently reviewed withdrawal manifest's exact UTF-8 bytes and SHA-256:
{"schema": "missioncore.mixed-withdrawals/v1", "evidence": [
{"path": "archive/member.json", "sha256": "<reviewed evidence hash>"}],
"records": {"<sample_id>": {"source": <entry source>, "input": <input>,
"old_target_sha256": "<old uint8 target bytes hash>",
"runs": [[row, inclusive_start, exclusive_end]]}}}
The manifest may cover a full release while records select a whole-street fold.
Every selected withdrawal must match exactly. Audit the complete release once
before splitting; no pixel count or location is an authorization. Evidence files
must be verified by the caller before pinning this manifest. Class/cohort masks
in existing records are historical; score them intersected with the final target.
"""
import hashlib
import json
import numpy as np
from admission_store import pixel_target
def _sha(value):
return hashlib.sha256(value).hexdigest()
def _hash(value):
return (
isinstance(value, str) and len(value) == 64 and all(c in "0123456789abcdef" for c in value)
)
def _withdrawals(payload, expected):
if payload is None and expected is None:
return {}
if not isinstance(payload, bytes) or not _hash(expected) or _sha(payload) != expected:
raise ValueError("Withdrawal manifest bytes differ from their frozen hash")
doc = json.loads(payload)
if (
doc.get("schema") != "missioncore.mixed-withdrawals/v1"
or not isinstance(doc.get("records"), dict)
or not isinstance(doc.get("evidence"), list)
or not doc["evidence"]
or any(
not isinstance(e, dict)
or not isinstance(e.get("path"), str)
or not e["path"]
or not _hash(e.get("sha256"))
for e in doc["evidence"]
)
):
raise ValueError("Pinned reviewed withdrawal evidence required")
return doc["records"]
def _target(entry, selected):
matches = [v for v in entry["targets"] if v["view"] == selected["view"]]
if len(matches) != 1:
raise ValueError("Exactly one target for the selected input view required")
view = matches[0]
if view["size"] != selected["camera"]["size"]:
raise ValueError("Target and selected image dimensions differ")
return np.frombuffer(pixel_target(view), dtype=np.uint8).reshape(tuple(view["size"][::-1]))
def _removals(proof, record, entry, before):
mask = np.zeros(before.shape, dtype=bool)
if proof is None:
return mask
if (
proof.get("source") != entry["source"]
or proof.get("input") != record["input"]
or proof.get("old_target_sha256") != _sha(before.tobytes())
or not isinstance(proof.get("runs"), list)
or not proof["runs"]
):
raise ValueError("Withdrawal evidence does not bind this source, view and old target")
height, width = before.shape
for run in proof["runs"]:
if (
not isinstance(run, list)
or len(run) != 3
or any(type(v) is not int for v in run)
or not 0 <= run[0] < height
or not 0 <= run[1] < run[2] <= width
):
raise ValueError("Withdrawal run outside selected native image")
row, start, end = run
if mask[row, start:end].any():
raise ValueError("Duplicate withdrawal pixels")
mask[row, start:end] = True
return mask
def prepare_mixed(
records, weights, old_entries, new_entries, *, withdrawal_bytes=None, withdrawal_sha256=None
):
"""Return copied records, name-keyed weights and JSON-serializable audit.
Only selected TRAIN sample IDs may appear in the entry mappings. Group/class
mass is conserved independently, never pooled across streets or classes.
A changed class shares its baseline mass equally across final supported
frames, then uniformly over that frame's class pixels. An unchanged class
retains its exact weights. Unknown always has zero mass. Added support with
no prior group/class mass, or withdrawal of all its support, fails closed.
"""
names = [r["name"] for r in records]
ids = [r["sample_id"] for r in records]
if (
not records
or len(set(names)) != len(names)
or len(set(ids)) != len(ids)
or set(names) != set(weights)
or set(ids) != set(old_entries)
or set(ids) != set(new_entries)
):
raise ValueError("Unique matching TRAIN records, weights and release entries required")
proofs = _withdrawals(withdrawal_bytes, withdrawal_sha256)
out, result, audit = [], {}, []
for record in records:
sid, name = record["sample_id"], record["name"]
old, new = old_entries[sid], new_entries[sid]
fields = ("sample_id", "source", "physical_group", "split", "task", "inputs")
if (
any(old[k] != new[k] for k in fields)
or old["sample_id"] != sid
or old["split"] != "train"
or record["split"] != "train"
or old["task"] != "observed_paint"
or old["physical_group"] != record["group"]
or not old["source"]
or old["inputs"].count(record["input"]) != 1
or record["input"]["sample_id"] != sid
or ("source" in record and record["source"] != old["source"])
):
raise ValueError("TRAIN source, sample, physical group or image binding changed")
before, after = _target(old, record["input"]), _target(new, record["input"])
target, weight = record["target"], weights[name]
if (
target.dtype != np.uint8
or target.shape != before.shape
or not np.array_equal(target, before)
or weight.shape != before.shape
or weight.dtype.kind != "f"
or not np.isfinite(weight).all()
or np.any(weight[before != 255] <= 0)
or np.any(weight[before == 255] != 0)
):
raise ValueError("Cached old target or known/unknown weight support differs")
removed = (before != 255) & (after == 255)
if np.any((before != 255) & (after != 255) & (before != after)):
raise ValueError("Known class flips are not mixed-supervision growth")
allowed = _removals(proofs.get(sid), record, old, before)
if not np.array_equal(removed, allowed):
raise ValueError("Withdrawals differ from the exact reviewed pixels")
paint, background = (before == 255) & (after == 1), (before == 255) & (after == 0)
out.append(
dict(
record,
target=after.copy(),
mixed_added_paint=paint,
mixed_added_background=background,
mixed_withdrawn=removed,
)
)
result[name] = weight.copy()
result[name][after == 255] = 0
audit.append(
dict(
name=name,
sample_id=sid,
group=record["group"],
old_target_sha256=_sha(before.tobytes()),
new_target_sha256=_sha(after.tobytes()),
added_paint=int(paint.sum()),
added_background=int(background.sum()),
withdrawn_paint=int((removed & (before == 1)).sum()),
withdrawn_background=int((removed & (before == 0)).sum()),
)
)
mass_audit = []
for group in sorted({r["group"] for r in records}):
paired = [(r, n) for r, n in zip(records, out, strict=True) if r["group"] == group]
for label in (0, 1):
mass = sum(
float(weights[r["name"]][r["target"] == label].sum(dtype=np.float64))
for r, _ in paired
)
changed = any(
not np.array_equal(r["target"] == label, n["target"] == label) for r, n in paired
)
present = [n for _, n in paired if np.any(n["target"] == label)]
if changed:
if mass <= 0 or not present:
raise ValueError("Changed group/class needs baseline mass and final support")
for n in present:
mask = n["target"] == label
result[n["name"]][mask] = mass / len(present) / int(mask.sum())
actual = sum(
float(result[n["name"]][n["target"] == label].sum(dtype=np.float64))
for _, n in paired
)
if not np.isclose(actual, mass, atol=1e-8, rtol=1e-6):
raise ValueError("Physical-group class mass changed")
mass_audit.append(
dict(
group=group,
label=label,
before=mass,
after=actual,
redistributed=changed,
supported_frames=len(present),
)
)
return out, result, dict(records=audit, masses=mass_audit, withdrawal_sha256=withdrawal_sha256)
@@ -0,0 +1,33 @@
"""Windows-owned conversion descendants die with the learning coordinator."""
import ctypes
from ctypes import wintypes
class NativeChildren:
def __init__(self):
self.kernel = ctypes.WinDLL("kernel32", use_last_error=True)
self.kernel.CreateJobObjectW.restype = wintypes.HANDLE
self.kernel.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
self.kernel.SetInformationJobObject.argtypes = [
wintypes.HANDLE,
ctypes.c_int,
ctypes.c_void_p,
wintypes.DWORD,
]
self.kernel.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
self.kernel.CloseHandle.argtypes = [wintypes.HANDLE]
self.handle = self.kernel.CreateJobObjectW(None, None)
limits = ctypes.create_string_buffer(144)
ctypes.c_uint32.from_buffer(limits, 16).value = 0x2000
if not self.handle or not self.kernel.SetInformationJobObject(self.handle, 9, limits, 144):
raise ctypes.WinError(ctypes.get_last_error())
def assign(self, process):
if not self.kernel.AssignProcessToJobObject(self.handle, int(process._handle)):
process.kill()
process.wait(timeout=30)
raise ctypes.WinError(ctypes.get_last_error())
def close(self):
self.kernel.CloseHandle(self.handle)
@@ -0,0 +1,255 @@
"""Shared native/low-pass RGB residual point head; offline, no fitting or IDs.
Native guidance is compared with area-downsampled/bilinear-upsampled guidance.
This changes spatial detail and local color mixing together. It does not prove
the cause of a prior model's boundary errors. Input fine/coarse maps are already
frozen and C4-averaged; only RGB patches receive the additional C4 operation here.
"""
from feature_refinement import sample_native
ARMS = frozenset({"native_rgb", "lowpass_rgb"})
PATCH_SIZE = 5
PATCH_CHANNELS = 3 * PATCH_SIZE * PATCH_SIZE
def _floating(value, name):
import torch
if not isinstance(value, torch.Tensor) or value.dtype not in {torch.float32, torch.float64}:
raise ValueError(f"{name} must be a float32/float64 tensor")
if value.requires_grad:
raise ValueError(f"{name} must be frozen without input gradients")
if not bool(torch.isfinite(value).all()):
raise ValueError(f"{name} must be finite")
def _rgb(rgb, *, centered):
_floating(rgb, "RGB")
if rgb.ndim != 4 or rgb.shape[:2] != (1, 3) or min(rgb.shape[-2:]) < 1:
raise ValueError("Expected nonempty RGB with shape (1, 3, H, W)")
lower = -1 if centered else 0
if not bool(((rgb >= lower) & (rgb <= 1)).all()):
raise ValueError(f"RGB must be in [{lower}, 1]")
def _shape(shape):
if (
not isinstance(shape, (tuple, list))
or len(shape) != 2
or any(type(size) is not int or size < 1 for size in shape)
):
raise ValueError("Feature shape must contain two positive integer dimensions")
return tuple(shape)
def _maps(fine, coarse, rgb):
_floating(fine, "Fine features")
_floating(coarse, "Coarse logits")
_rgb(rgb, centered=True)
if fine.ndim != 4 or fine.shape[0] != 1 or min(fine.shape[1:]) < 1:
raise ValueError("Expected one nonempty fine feature map (1, C, h, w)")
if coarse.ndim != 2 or min(coarse.shape) < 1 or rgb.shape[-2:] != coarse.shape:
raise ValueError("Coarse logits and RGB must have the same nonempty native shape")
for value in (coarse, rgb):
if value.dtype != fine.dtype or value.device != fine.device:
raise ValueError("Fine, coarse and RGB must share a dtype and device")
def _indices(indices, shape, device):
import torch
if (
not isinstance(indices, torch.Tensor)
or indices.ndim != 1
or indices.dtype != torch.long
or indices.device != device
):
raise ValueError("Expected flat int64 native indices on the image device")
if len(indices) and (bool((indices < 0).any()) or bool((indices >= shape[0] * shape[1]).any())):
raise ValueError("Point outside the native image")
def _patch(patch):
_floating(patch, "RGB patch")
if patch.ndim != 2 or patch.shape[1] != PATCH_CHANNELS:
raise ValueError("Expected RGB patches with shape (N, 75)")
if not bool(((patch >= -1) & (patch <= 1)).all()):
raise ValueError("Centered RGB patches must be in [-1, 1]")
def network(seed, channels=256, width=64):
"""Two shared Linear/ReLU layers with coarse concatenated at every layer.
Default parameter count is 25,602. The final layer is zero initialized, so
output is exactly the supplied coarse logit before fitting. Initialization is
on CPU and preserves the calling CPU RNG state; no CUDA RNG is reseeded.
"""
import torch
from torch import nn
if any(type(value) is not int or value < 1 for value in (channels, width)):
raise ValueError("Positive integer feature channel count and width required")
class Head(nn.Module):
def __init__(self):
super().__init__()
self.layers = nn.ModuleList(
[
nn.Linear(channels + PATCH_CHANNELS + 1, width, device="cpu"),
nn.Linear(width + 1, width, device="cpu"),
]
)
self.output = nn.Linear(width + 1, 1, device="cpu")
for layer in self.layers:
nn.init.kaiming_normal_(layer.weight, nonlinearity="relu")
nn.init.zeros_(layer.bias)
nn.init.zeros_(self.output.weight)
nn.init.zeros_(self.output.bias)
def forward(self, fine, coarse, patch):
_floating(fine, "Fine points")
_floating(coarse, "Coarse points")
_patch(patch)
if fine.ndim != 2 or fine.shape[1] != channels:
raise ValueError("Expected points by fine channels")
if coarse.shape != (len(fine), 1) or len(patch) != len(fine):
raise ValueError("Fine, coarse and RGB points must be aligned")
for value in (fine, coarse, patch):
if (
value.dtype != self.output.weight.dtype
or value.device != self.output.weight.device
):
raise ValueError("Point inputs and head must share a dtype and device")
x = torch.cat((fine, patch), dim=1)
for layer in self.layers:
x = torch.relu(layer(torch.cat((x, coarse), dim=1)))
return coarse + self.output(torch.cat((x, coarse), dim=1))
with torch.random.fork_rng(devices=[]):
torch.random.default_generator.manual_seed(seed)
return Head()
def prepare_rgb(rgb, feature_shape, arm):
"""Prepare native-sized centered guidance once, before point sampling.
Input RGB is floating (1, 3, H, W) in [0, 1]. Low-pass uses the actual frozen
feature grid (normally 128x128), area downsampling, then bilinear upsampling
with align_corners=False. Both arms then apply (RGB - .5) / .5; no learned or
held-image statistics. The feature grid must not exceed either native axis.
"""
from torch.nn import functional as F
if arm not in ARMS:
raise ValueError("Unknown native-detail arm")
_rgb(rgb, centered=False)
feature_shape = _shape(feature_shape)
native_shape = rgb.shape[-2:]
if any(a > b for a, b in zip(feature_shape, native_shape, strict=True)):
raise ValueError("The low-pass feature grid must not exceed the native image")
guidance = rgb
if arm == "lowpass_rgb":
guidance = F.interpolate(guidance, size=feature_shape, mode="area")
guidance = F.interpolate(
guidance, size=native_shape, mode="bilinear", align_corners=False
)
return (guidance - 0.5) / 0.5
def _sample_patch(rgb, indices):
import torch
h, w = rgb.shape[-2:]
offsets = torch.arange(-2, 3, device=rgb.device)
ys = torch.div(indices, w, rounding_mode="floor")
xs = indices % w
rows = (ys[:, None, None] + offsets[None, :, None]).clamp(0, h - 1)
cols = (xs[:, None, None] + offsets[None, None, :]).clamp(0, w - 1)
# Shape C,N,5,5 -> N,C,5,5, never a full-image unfold allocation.
return rgb[0][:, rows, cols].permute(1, 0, 2, 3).reshape(len(indices), PATCH_CHANNELS)
def sample_patch(prepared_rgb, indices):
"""Sample centered 5x5 patches at integer native pixel centres.
Flattening is channel-major: R's 25 values, G's 25, then B's 25. Within each
channel, row-major offsets are dy=-2..2, dx=-2..2. Out-of-image offsets clamp
independently to the nearest valid row/column (replicate border).
"""
_rgb(prepared_rgb, centered=True)
_indices(indices, prepared_rgb.shape[-2:], prepared_rgb.device)
return _sample_patch(prepared_rgb, indices)
def _rotate_patch(patch, k):
import torch
return torch.rot90(patch.reshape(-1, 3, PATCH_SIZE, PATCH_SIZE), k, (-2, -1)).reshape(
len(patch), PATCH_CHANNELS
)
def rotate_patch(flat_patch, k):
"""Rotate each RGB patch k quarter-turns counterclockwise; keep RGB order.
k is exactly 0, 1, 2 or 3. Only the two 5x5 spatial axes rotate. Fine features,
coarse logits, centre labels and point order are unchanged. The runner owns
training's shared k=step%4 schedule; no rotation is selected from image data.
"""
_patch(flat_patch)
if type(k) is not int or k not in range(4):
raise ValueError("Patch rotation must be an integer from 0 through 3")
return _rotate_patch(flat_patch, k)
def _sample_points(fine, coarse, prepared_rgb, indices):
if not len(indices):
return (
fine.new_empty((0, fine.shape[1])),
coarse.new_empty((0, 1)),
prepared_rgb.new_empty((0, PATCH_CHANNELS)),
)
return (
sample_native(fine, coarse.shape, indices),
coarse.reshape(-1, 1)[indices],
_sample_patch(prepared_rgb, indices),
)
def sample_points(fine, coarse, prepared_rgb, indices):
"""Return frozen (fine points, coarse points, RGB patches) for a fit runner.
Fine sampling delegates to feature_refinement.sample_native, which uses
bilinear interpolation at native pixel centres with align_corners=False.
Integer indices are addressing only and never enter the learned head.
"""
_maps(fine, coarse, prepared_rgb)
_indices(indices, coarse.shape, fine.device)
return _sample_points(fine, coarse, prepared_rgb, indices)
def predict(net, fine, coarse, rgb, arm, chunk=8192):
"""Native-resolution logits, averaging all four patch rotations per point.
Coarse + mean(logit_k - coarse) is the mean of the four logits, computed with
a common coarse offset to preserve exact zero-residual identity. There are no
reflections, fine/coarse rotations, inferred orientations or learned resize.
Guidance is prepared once; only the current chunk's patches are materialized.
"""
import torch
if type(chunk) is not int or chunk < 1:
raise ValueError("Positive integer prediction chunk required")
_maps(fine, coarse, rgb)
prepared = prepare_rgb(rgb, fine.shape[-2:], arm)
out = []
with torch.inference_mode():
for start in range(0, coarse.numel(), chunk):
indices = torch.arange(
start, min(start + chunk, coarse.numel()), device=fine.device
)
points, logits, patch = _sample_points(fine, coarse, prepared, indices)
corrections = [net(points, logits, _rotate_patch(patch, k)) - logits for k in range(4)]
out.append((logits + torch.stack(corrections).mean(0))[:, 0])
return torch.cat(out).reshape(coarse.shape)
@@ -0,0 +1,58 @@
"""Bounded native-grid logit inference for one image, independent of scene IDs.
The predictor sees every tile. Labels and visibility masks are not inputs.
Overlaps average logits uniformly; softmax/threshold belongs to the caller.
"""
import numpy as np
def starts(length, tile, stride, *, limit=4096):
if any(type(v) is not int or v <= 0 for v in (length, tile, stride)) or stride > tile:
raise ValueError("Positive integer extent and stride <= tile required")
last = max(0, length - tile)
count = last // stride + 1 + bool(last % stride)
if type(limit) is not int or not 1 <= limit <= 4096 or count > limit:
raise ValueError("Tile grid budget exceeded")
return sorted(set(range(0, last + 1, stride)) | {last})
def sliding_logits(rgb, predict, *, tile=512, stride=256, classes=2,
max_pixels=4_194_304, max_tiles=256):
if (not isinstance(rgb, np.ndarray) or rgb.ndim != 3
or rgb.shape[2] != 3 or rgb.dtype != np.uint8):
raise ValueError("Native uint8 RGB required")
h, w = rgb.shape[:2]
if type(classes) is not int or not 1 <= classes <= 256:
raise ValueError("Bounded class count required")
if (type(max_pixels) is not int or type(max_tiles) is not int
or max_pixels <= 0 or not 1 <= max_tiles <= 4096 or h * w > max_pixels):
raise ValueError("Raster resource budget exceeded")
if type(tile) is not int or tile <= 0 or tile * tile > max_pixels:
raise ValueError("Tile working budget exceeded")
ys = starts(h, tile, stride, limit=max_tiles)
xs = starts(w, tile, stride, limit=max_tiles)
if len(ys) * len(xs) > max_tiles:
raise ValueError("Tile budget exceeded")
result = np.zeros((classes, h, w), np.float32)
counts = np.zeros((h, w), np.uint32)
for y in ys:
for x in xs:
hh, ww = min(tile, h-y), min(tile, w-x)
crop = np.zeros((tile, tile, 3), np.uint8)
crop[:hh, :ww] = rgb[y:y+hh, x:x+ww]
logits = np.asarray(predict(crop))
if (logits.shape != (classes, tile, tile)
or logits.dtype not in (np.float16, np.float32, np.float64)
or not np.isfinite(logits).all()):
raise ValueError("Predictor must return finite native class logits")
result[:, y:y+hh, x:x+ww] += logits[:, :hh, :ww].astype(np.float32)
counts[y:y+hh, x:x+ww] += 1
if not counts.all():
raise ValueError("Incomplete native coverage")
result /= counts[None]
if not np.isfinite(result).all():
raise ValueError("Accumulation overflow")
return result, dict(tile=tile, stride=stride, tiles=len(ys)*len(xs),
size=[w, h], minimum_overlap=int(counts.min()),
maximum_overlap=int(counts.max()),
aggregation="uniform_mean_native_class_logits")
@@ -0,0 +1,70 @@
"""TRAIN-only grouped score thresholds. Outer/evaluation labels are not inputs."""
import numpy as np
from score_diagnostic import curve, matched
def nested_folds(groups):
groups = list(groups)
if len(groups) < 3 or any(not isinstance(g, str) or not g for g in groups):
raise ValueError("At least three named groups required")
if len(set(groups)) != len(groups):
raise ValueError("Duplicate physical group")
return [
dict(outer=outer, inner=inner, training_groups=sorted(set(groups) - {outer, inner}))
for outer in sorted(groups)
for inner in sorted(set(groups) - {outer})
]
def calibrate_inner(rows, outer, groups):
"""One threshold per family obeying every inner-street background budget.
Each row aggregates one held-inner street and contains only its scores and
reviewed masks. Equal scores are indivisible; unreviewed pixels never supply
a threshold candidate. Both families receive the same old-fixed0 budgets.
"""
plans = [p for p in nested_folds(groups) if p["outer"] == outer]
if not plans or len(rows) != len(plans):
raise ValueError("Complete inner folds for a known outer group required")
by_group = {r["group"]: r for r in rows}
if len(by_group) != len(rows) or set(by_group) != {p["inner"] for p in plans}:
raise ValueError("Inner streets must exclude outer and cover the permitted groups")
arrays, masks, budgets, ids = [], [], {}, set()
for plan in plans:
r = by_group[plan["inner"]]
expected = plan["training_groups"]
if (
sorted(r["training_groups"]) != expected
or sorted(r["initialization_groups"]) != expected
):
raise ValueError("Fit and initialization must exclude both held streets")
if r["split"] != "train" or not r["sample_ids"]:
raise ValueError("Only identified TRAIN observations may calibrate")
if len(set(r["sample_ids"])) != len(r["sample_ids"]) or ids.intersection(r["sample_ids"]):
raise ValueError("Duplicate calibration observation")
ids.update(r["sample_ids"])
old, new = np.asarray(r["old"]), np.asarray(r["new"])
if old.shape != new.shape:
raise ValueError("Paired scores must align")
pos = {"paint": r["paint"]}
neg = {k: r[k] for k in ["original_bg", "added_bg"]}
curve(old, pos, neg)
curve(new, pos, neg)
arrays.append((old, new))
masks.append((r["paint"], neg))
for part, mask in neg.items():
budgets[r["group"] + "/" + part] = int(np.count_nonzero((old >= 0) & mask))
lengths = [len(a[0]) for a in arrays]
positive = {"paint": np.concatenate([m[0] for m in masks])}
negative = {}
for i, plan in enumerate(plans):
for part in ["original_bg", "added_bg"]:
negative[plan["inner"] + "/" + part] = np.concatenate(
[masks[j][1][part] if i == j else np.zeros(n, bool) for j, n in enumerate(lengths)]
)
points = {}
for i, origin in enumerate(["old", "new"]):
c = curve(np.concatenate([a[i] for a in arrays]), positive, negative)
points[origin] = matched(c, budgets)
return dict(outer=outer, calibration_groups=sorted(by_group), budgets=budgets, **points)
@@ -0,0 +1,423 @@
"""Fixed-data nonlinear capacity probe. Identities/coordinates never enter the head."""
import argparse
import json
import time
from pathlib import Path
import numpy as np
from pixel_growth_probe import aggregate, balanced_weights, counts, fit, resize_plane
from scipy.optimize import minimize
from scipy.special import expit
from supervision_density_probe import samples
def training_arrays(units):
if not units or any(u["split"] != "train" for u in units):
raise ValueError("Only nonempty training units may fit the head")
x = np.concatenate([u["x"] for u in units]).astype(float)
y = np.concatenate([u["y"] for u in units])
if x.ndim != 2 or len(x) != len(y) or not np.isfinite(x).all():
raise ValueError("Invalid training features")
weight = balanced_weights(units)
mean = (x * weight[:, None]).sum(0)
scale = np.maximum(np.sqrt(((x - mean) ** 2 * weight[:, None]).sum(0)), 1e-5)
return (x - mean) / scale, y, weight, mean, scale
def unpack(theta, dimensions, hidden):
end = dimensions * hidden
return (
theta[:end].reshape(dimensions, hidden),
theta[end : end + hidden],
theta[end + hidden : end + 2 * hidden],
theta[-1],
)
def objective(theta, x, y, weight, hidden, l2):
w1, b1, w2, b2 = unpack(theta, x.shape[1], hidden)
a = np.tanh(x @ w1 + b1)
z = a @ w2 + b2
loss = np.sum(weight * (np.logaddexp(0, z) - y * z)) + l2 * (np.sum(w1 * w1) + w2 @ w2) / 2
dz = weight * (expit(z) - y)
da = dz[:, None] * w2[None] * (1 - a * a)
grad = np.concatenate([(x.T @ da + l2 * w1).ravel(), da.sum(0), a.T @ dz + l2 * w2, [dz.sum()]])
return float(loss), grad
def fit_mlp(units, hidden, seed, l2, max_iterations, progress=None, timeout=180):
start = time.monotonic()
x, y, weight, mean, scale = training_arrays(units)
dimensions = x.shape[1]
rng = np.random.default_rng(seed)
initial = np.concatenate(
[
rng.normal(0, np.sqrt(2 / (dimensions + hidden)), dimensions * hidden),
np.zeros(hidden),
rng.normal(0, np.sqrt(2 / (hidden + 1)), hidden),
[0.0],
]
)
state = dict(theta=initial.copy(), iterations=0)
def callback(theta):
state["theta"] = theta.copy()
state["iterations"] += 1
if progress and state["iterations"] % 10 == 0:
progress(
dict(
seed=seed,
iterations=state["iterations"],
elapsed_seconds=time.monotonic() - start,
)
)
if time.monotonic() - start > timeout:
raise TimeoutError("Predeclared fitting wall-clock budget exceeded")
try:
result = minimize(
objective,
initial,
args=(x, y, weight, hidden, l2),
jac=True,
method="L-BFGS-B",
callback=callback,
options={"maxiter": max_iterations},
)
theta, success, message = result.x, bool(result.success), str(result.message)
iterations, evaluations = int(result.nit), int(result.nfev)
except TimeoutError as exc:
theta, success, message = state["theta"], False, str(exc)
iterations, evaluations = state["iterations"], None
loss, grad = objective(theta, x, y, weight, hidden, l2)
w1, b1, w2, b2 = unpack(theta, dimensions, hidden)
return dict(
kind="mlp",
hidden=hidden,
seed=seed,
activation="tanh",
mean=mean.tolist(),
scale=scale.tolist(),
w1=w1.tolist(),
b1=b1.tolist(),
w2=w2.tolist(),
b2=float(b2),
iterations=iterations,
evaluations=evaluations,
converged=success,
message=message,
objective=loss,
gradient_inf_norm=float(np.max(np.abs(grad))),
samples=len(y),
training_groups=sorted({u["group"] for u in units}),
seconds=time.monotonic() - start,
production_eligible=False,
)
def mlp_logits(x, model, normalized=False):
if not normalized:
x = (np.asarray(x, dtype=float) - np.array(model["mean"])) / np.array(model["scale"])
return (
np.tanh(x @ np.array(model["w1"]) + np.array(model["b1"])) @ np.array(model["w2"])
+ model["b2"]
)
def native_mlp_predictions(features, size, models, threshold, rows=32):
"""Evaluate the nonlinear function after interpolating features, as during fit."""
import torch
h, w = size
mean, scale = (
np.array(next(iter(models.values()))["mean"]),
np.array(next(iter(models.values()))["scale"]),
)
if any(
not np.array_equal(mean, m["mean"]) or not np.array_equal(scale, m["scale"])
for m in models.values()
):
raise ValueError("Model normalization differs")
source = torch.from_numpy(features)[None]
predictions = {name: np.empty((h, w), dtype=bool) for name in models}
for top in range(0, h, rows):
yy, xx = np.meshgrid(np.arange(top, min(top + rows, h)), np.arange(w), indexing="ij")
grid = np.stack([2 * (xx + 0.5) / w - 1, 2 * (yy + 0.5) / h - 1], -1).astype("float32")
sampled = (
torch.nn.functional.grid_sample(
source,
torch.from_numpy(grid)[None],
mode="bilinear",
padding_mode="border",
align_corners=False,
)[0]
.permute(1, 2, 0)
.reshape(-1, features.shape[0])
.numpy()
)
x = (sampled.astype(float) - mean) / scale
for name, model in models.items():
predictions[name][top : top + len(yy)] = (
expit(mlp_logits(x, model, normalized=True)) >= threshold
).reshape(yy.shape)
return predictions
def qualify(metrics, diagnostic, candidates, converged, reproduced, historical):
trials = {}
for name in candidates:
failures, historical_failures = [], []
if not reproduced:
failures.append("linear baseline reproduction")
if not converged[name]:
failures.append("optimizer did not converge")
for group, variants in metrics.items():
for metric, sign in [("recall", 1), ("fpr", -1)]:
value = variants[name][metric]
for reference, destination in [
(variants["linear"], failures),
(historical[group], historical_failures),
]:
if (
value is not None
and reference[metric] is not None
and sign * (value - reference[metric]) < -1e-12
):
destination.append(group + ": " + metric)
if diagnostic[name]["recall"] < diagnostic["linear"]["recall"]:
failures.append("P1 diagnostic paint recall")
if diagnostic[name]["fpr"] >= diagnostic["linear"]["fpr"]:
failures.append("P1 gap FPR not strictly improved")
trials[name] = dict(
accepted=not failures,
failures=failures,
historical_regressions_repaired=not historical_failures,
historical_failures=historical_failures,
)
return dict(
capacity_test_passed=all(t["accepted"] for t in trials.values()),
historical_repair_all_seeds=all(
t["historical_regressions_repaired"] for t in trials.values()
),
trials=trials,
selected_model=None,
production_eligible=False,
)
def checked_setup(root, store):
from dataset_store import checksum, read
p, frozen, f = (
read(root / "protocol.json"),
read(root / "review-frozen.json"),
read(root / "feature-manifest.json"),
)
parent = store / "experiments" / p["parent"]
assert frozen["source_sha256"] == checksum(Path(__file__))
assert frozen["protocol_sha256"] == f["protocol_sha256"] == checksum(root / "protocol.json")
assert (
read(root / "supervision-receipt.json")
== read(parent / "supervision-receipt.json")
== frozen["supervision"]
== f["supervision"]
)
assert f["supervision"]["sha256"] == p["parent_release_sha256"]
assert p["fit"] == read(parent / "protocol.json")["fit"]
assert checksum(root / "model-inventory.json") == checksum(parent / "model-inventory.json")
assert (
frozen["audit_sha256"]
== checksum(root / "p1-audit-runs-final.json")
== checksum(parent / "p1-audit-runs-final.json")
)
old = {r["sample_id"]: r for r in read(parent / "feature-manifest.json")["records"]}
assert set(old) == {r["sample_id"] for r in f["records"]}
for r in f["records"]:
# NPZ identity covers features and targets; identical extraction is required.
for key in ["name", "group", "split", "input", "target_sha256", "size", "sha256"]:
assert r[key] == old[r["sample_id"]][key], key
assert checksum(root / r["cache"]) == r["sha256"]
return p, f, parent
def fit_stage(root, store):
import torch
from dataset_store import checksum, read, write
torch.set_num_threads(3)
p, f, parent = checked_setup(root, store)
assert not (root / "models-frozen.json").exists()
units = []
for r in f["records"]:
if r["split"] == "train":
with np.load(root / r["cache"]) as z:
units.append(samples(z["features"].astype("float32"), z["target"], r, p["fit"]))
models = dict(linear=fit(units, p["fit"]["l2"], p["fit"]["max_iterations"]))
old = read(parent / "models-frozen.json")["models"]["expanded"]
delta = max(
float(np.max(np.abs(np.array(models["linear"][k]) - np.array(old[k]))))
for k in ["mean", "scale", "coefficients"]
)
assert delta == 0, "linear baseline parameters changed"
config = p["nonlinear"]
for seed in config["seeds"]:
write(root / "fit-progress.json", dict(seed=seed, iterations=0))
m = fit_mlp(
units,
config["hidden"],
seed,
config["l2"],
config["max_iterations"],
progress=lambda status: write(root / "fit-progress.json", status),
timeout=config["fitting_timeout_per_seed_seconds"],
)
assert m["mean"] == models["linear"]["mean"] and m["scale"] == models["linear"]["scale"]
models["mlp-" + str(seed)] = m
print(
json.dumps(
dict(
seed=seed,
converged=m["converged"],
iterations=m["iterations"],
seconds=m["seconds"],
)
),
flush=True,
)
write(
root / "models-frozen.json",
dict(
models=models,
threshold=p["fit"]["threshold"],
source_sha256=checksum(Path(__file__)),
protocol_sha256=checksum(root / "protocol.json"),
features_sha256=checksum(root / "feature-manifest.json"),
review_sha256=checksum(root / "review-frozen.json"),
baseline_max_parameter_delta=delta,
frozen_before_evaluation=True,
),
)
def evaluate_stage(root, store):
import torch
from admission_store import pixel_target
from dataset_store import checksum, read, write
torch.set_num_threads(3)
start = time.monotonic()
p, f, parent = checked_setup(root, store)
assert not (root / "result.json").exists()
frozen = read(root / "models-frozen.json")
for key, name in [
("source_sha256", Path(__file__)),
("features_sha256", root / "feature-manifest.json"),
("protocol_sha256", root / "protocol.json"),
("review_sha256", root / "review-frozen.json"),
]:
assert frozen[key] == checksum(name)
models = frozen["models"]
candidates = {k: m for k, m in models.items() if k != "linear"}
rows, train_rows, diagnostic = [], [], None
for r in f["records"]:
with np.load(root / r["cache"]) as z:
features, target = z["features"].astype("float32"), z["target"]
m = models["linear"]
coef = np.array(m["coefficients"])
scaled = coef[1:] / np.array(m["scale"])
bias = coef[0] - np.array(m["mean"]) @ scaled
predictions = dict(
linear=expit(
resize_plane(
(np.einsum("chw,c->hw", features, scaled) + bias)[None], target.shape
)[0]
)
>= p["fit"]["threshold"]
)
predictions.update(
native_mlp_predictions(features, target.shape, candidates, p["fit"]["threshold"])
)
np.savez_compressed(root / "cache" / (r["name"] + "-predictions.npz"), **predictions)
row = dict(
name=r["name"],
group=r["group"],
variants={k: counts(pred, target) for k, pred in predictions.items()},
)
(rows if r["split"] == "regression" else train_rows).append(row)
if r["name"] == "P1":
audit = np.frombuffer(
pixel_target(dict(read(root / "p1-audit-runs-final.json"), size=[512, 512])),
dtype="uint8",
).reshape(512, 512)
diagnostic = {
k: aggregate([counts(pred, audit)]) for k, pred in predictions.items()
}
write(
root / "eval-progress.json",
dict(last_completed=r["name"], elapsed_seconds=time.monotonic() - start),
)
metrics = {
g: {arm: aggregate([r["variants"][arm] for r in rows if r["group"] == g]) for arm in models}
for g in sorted({r["group"] for r in rows})
}
old = read(parent / "result.json")
old_rows = {r["name"]: r for r in old["rows"]}
reproduced = (
frozen["baseline_max_parameter_delta"] == 0
and all(
r["variants"]["linear"] == old_rows[r["name"]]["variants"]["expanded"] for r in rows
)
and diagnostic["linear"] == old["diagnostic"]["expanded"]
)
historical = {
g: m["dense"]
for g, m in read(store / "experiments/semantic-dense-20261023/result.json")[
"metrics"
].items()
}
outcome = qualify(
metrics,
diagnostic,
list(candidates),
{k: m["converged"] for k, m in candidates.items()},
reproduced,
historical,
)
result = dict(
**outcome,
rows=rows,
train_rows=train_rows,
metrics=metrics,
diagnostic=diagnostic,
baseline_reproduced=reproduced,
baseline_max_parameter_delta=frozen["baseline_max_parameter_delta"],
models_sha256=checksum(root / "models-frozen.json"),
source_sha256=checksum(Path(__file__)),
protocol_sha256=checksum(root / "protocol.json"),
eval_seconds=time.monotonic() - start,
evaluated_utc=__import__("datetime")
.datetime.now(__import__("datetime").timezone.utc)
.isoformat(),
blind_generalization_claim=False,
)
write(root / "result.json", result)
print(
json.dumps(
{
**outcome,
"metrics": metrics,
"diagnostic": diagnostic,
"baseline_reproduced": reproduced,
}
)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("stage", choices=["fit", "evaluate"])
parser.add_argument("root", type=Path)
parser.add_argument("--store", type=Path, default=Path("/store"))
args = parser.parse_args()
(fit_stage if args.stage == "fit" else evaluate_stage)(args.root, args.store)
@@ -0,0 +1,418 @@
"""Bounded single-view assembly/learning experiment, never a map publisher.
Inputs, annotation, policy, model selection and held-out evaluation are separate.
The retained two-view downstream row fitter is NOT qualified by this experiment.
"""
import json
import sys
from pathlib import Path
import cv2
import numpy as np
from object_proposal_study import (
aggregate,
descriptors,
labels,
masks,
overlap,
save_new,
score,
sha,
timestamp,
)
from object_proposal_study import (
propose as base_propose,
)
from paint_hypothesis_study import fit_classifier, probability
from PIL import Image
from shapely.geometry import mapping, shape
from shapely.ops import unary_union
MODEL_SIZES = {"expanded_shape_appearance": 14, "expanded_texture": 22}
def rectangle(poly, mpp):
box = np.asarray(poly.minimum_rotated_rectangle.exterior.coords)[:4]
edges = np.roll(box, -1, axis=0) - box
lengths = np.linalg.norm(edges, axis=1)
k = int(np.argmax(lengths))
axis = edges[k] / max(lengths[k], 1e-9)
if axis[0] < 0 or (axis[0] == 0 and axis[1] < 0):
axis = -axis
return dict(
center=box.mean(axis=0),
axis=axis,
length=float(lengths.max() * mpp),
width=float(lengths.min() * mpp),
fill=poly.area / max(poly.minimum_rotated_rectangle.area, 1e-9),
)
def texture(poly, rgb):
mask = masks(poly.minimum_rotated_rectangle)
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32)
residual = gray - cv2.GaussianBlur(gray, (0, 0), 0.35 * 512 / 12)
gx = cv2.Sobel(gray, cv2.CV_32F, 1, 0)
gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1)
mag = np.hypot(gx, gy)[mask]
xx, yy, xy = np.mean(gx[mask] ** 2), np.mean(gy[mask] ** 2), np.mean(gx[mask] * gy[mask])
coherence = np.hypot(xx - yy, 2 * xy) / max(xx + yy, 1e-9)
values = [
gray[mask].std() / 255,
residual[mask].std() / 255,
(np.quantile(gray[mask], 0.9) - np.quantile(gray[mask], 0.1)) / 255,
np.mean(gray[mask] < 75),
mag.mean() / 1020,
np.quantile(mag, 0.9) / 1020,
coherence,
np.mean(cv2.Canny(gray.astype(np.uint8), 40, 100)[mask] > 0),
]
return [float(v) for v in values]
def evidence_masks(rgb, fields, policy):
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32)
hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)
contrast = gray - cv2.GaussianBlur(gray, (0, 0), 0.35 / policy["mpp"])
white = (gray > 80) & (hsv[..., 1] < 100) & (contrast > 3)
yellow = (
(hsv[..., 0] > 12) & (hsv[..., 0] < 40) & (hsv[..., 1] > 40) & (gray > 70) & (contrast > 2)
)
size = max(3, int(0.25 / policy["mpp"]))
vehicles = cv2.dilate(
(fields["vehicle"] > 0.25).astype(np.uint8), np.ones((size, size), np.uint8)
)
return white | yellow, (fields["alpha"] > 0.65) & (vehicles == 0)
def linear_descriptor(poly, policy):
d = rectangle(poly, policy["mpp"])
if (
policy["min_length"] <= d["length"] <= policy["max_length"]
and policy["min_width"] <= d["width"] <= policy["max_width"]
and d["length"] / max(d["width"], 1e-9) >= policy["min_aspect"]
and d["fill"] >= policy["min_fill"]
):
return d
return None
def pair_allowed(p, q, a, b, policy):
if abs(a["axis"] @ b["axis"]) < np.cos(np.deg2rad(policy["max_pair_angle_deg"])):
return False
if max(a["width"], b["width"]) / min(a["width"], b["width"]) > policy["max_pair_width_ratio"]:
return False
normal = np.array([-a["axis"][1], a["axis"][0]])
lateral = abs((b["center"] - a["center"]) @ normal) * policy["mpp"]
if lateral > policy["max_pair_lateral_fraction"] * min(a["width"], b["width"]):
return False
return p.distance(q) * policy["mpp"] <= policy["max_join_gap"]
def supported_envelope(source, weak, physical, policy):
# Convex-envelope intersection cannot extrapolate beyond original observations.
proposed = source.minimum_rotated_rectangle.intersection(source.convex_hull)
if proposed.geom_type != "Polygon" or proposed.area <= 0:
return None, "non_polygon"
desc = linear_descriptor(proposed, policy)
if desc is None or source.area / proposed.area < policy["min_group_fill"]:
return None, "geometry"
mask = masks(proposed)
original = np.zeros_like(mask)
for p in [source] if source.geom_type == "Polygon" else source.geoms:
original |= masks(p)
added = mask & ~original
if np.mean(physical[mask]) < policy["min_physical_valid"]:
return None, "physical"
if np.mean(weak[mask]) < policy["min_total_weak_paint"]:
return None, "total_paint"
if added.any() and np.mean(weak[added]) < policy["min_added_weak_paint"]:
return None, "added_paint"
return proposed, "supported"
def assemble(candidates, rgb, fields, policy):
out = [
dict(c, features=c["features"][:14] + texture(shape(c["geometry"]), rgb))
for c in candidates
]
polys = [shape(c["geometry"]) for c in candidates]
desc = [linear_descriptor(p, policy) for p in polys]
parent = list(range(len(polys)))
def find(i):
while parent[i] != i:
i = parent[i]
return i
for i in range(len(polys)):
for j in range(i):
if desc[i] and desc[j] and pair_allowed(polys[i], polys[j], desc[i], desc[j], policy):
a, b = find(i), find(j)
parent[max(a, b)] = min(a, b)
groups = {}
for i, d in enumerate(desc):
if d:
groups.setdefault(find(i), []).append(i)
weak, physical = evidence_masks(rgb, fields, policy)
audit = []
def append(poly, members, kind):
if any(overlap(poly, shape(c["geometry"])) > 0.95 for c in out):
return
out.append(
dict(
id="assembled-" + str(len(out)),
geometry=mapping(poly),
properties=dict(kind=kind, parent_ids=[candidates[i]["id"] for i in members]),
features=descriptors(poly, rgb, fields)[:14] + texture(poly, rgb),
fixed_admitted=any(candidates[i]["fixed_admitted"] for i in members),
)
)
for ids in groups.values():
if len(ids) > policy["max_group"]:
audit.append(dict(parents=ids, verdict="group_limit"))
continue
union = unary_union([polys[i] for i in ids])
if len(ids) > 1:
for p in [union] if union.geom_type == "Polygon" else union.geoms:
if p.geom_type == "Polygon":
append(p, ids, "exact_union")
fitted, verdict = supported_envelope(union, weak, physical, policy)
audit.append(dict(parents=ids, verdict=verdict))
if fitted is not None:
append(fitted, ids, "supported_envelope")
return out, audit
def merged_count(candidates, reviewed):
truth = [shape(o["geometry"]) for o in reviewed["objects"] if o["complete"]]
return sum(
sum(shape(c["geometry"]).intersection(t).area / max(t.area, 1e-9) >= 0.2 for t in truth)
>= 2
for c in candidates
)
def measured(candidates, reviewed):
result = score(candidates, reviewed)
result["merged"] = int(merged_count(candidates, reviewed))
return result
def pooled(rows):
result = aggregate(rows)
result["merged"] = sum(r["merged"] for r in rows)
return result
def admitted(record, assembly, scorer, model=None, threshold=0):
channel = "hard" if scorer == "fixed_admission" else "retained"
cs = record["variants"][channel + "_" + assembly]
if scorer == "fixed_admission":
return [c for c in cs if c["fixed_admitted"]]
count = 14 if scorer == "previous_shape_appearance" else MODEL_SIZES[scorer]
ps = probability(np.array([c["features"][:count] for c in cs]), model) if cs else []
return [c for c, p in zip(cs, ps, strict=True) if p >= threshold]
def fit_models(records, review, thresholds):
train = [a for a in records if a["split"] == "train"]
val = [a for a in records if a["split"] == "validation"]
x, y = [], []
for a in train:
cs = a["variants"]["retained_on"]
for c, label in zip(cs, labels(cs, review[a["id"]]), strict=True):
if label >= 0:
x.append(c["features"])
y.append(label)
x, y = np.asarray(x), np.asarray(y)
if min(np.sum(y == 0), np.sum(y == 1)) < 2:
raise ValueError("Insufficient reviewed training examples")
baselines = {
arm: pooled([measured(admitted(a, arm, "fixed_admission"), review[a["id"]]) for a in val])
for arm in ["off", "on"]
}
models, choices = {}, []
for name, count in MODEL_SIZES.items():
model = fit_classifier(x[:, :count], y, 0.01, 500)
arms = {}
for arm in ["off", "on"]:
rows = []
for threshold in thresholds:
result = pooled(
[
measured(admitted(a, arm, name, model, threshold), review[a["id"]])
for a in val
]
)
rows.append(dict(threshold=threshold, **result))
feasible = [
v
for v in rows
if v["unsupported"] <= baselines[arm]["unsupported"]
and v["merged"] <= baselines[arm]["merged"]
]
selected = (
min(feasible, key=lambda v: (-v["found"], v["unsupported"], -v["threshold"]))
if feasible
else None
)
arms[arm] = dict(selected=selected, grid=rows)
if selected:
choices.append(dict(scorer=name, assembly=arm, feature_count=count, **selected))
models[name] = dict(model=model, arms=arms)
chosen = (
min(
choices,
key=lambda v: (
-v["found"],
v["unsupported"],
v["feature_count"],
v["assembly"] != "off",
),
)
if choices
else None
)
return dict(
models=models,
chosen=chosen,
validation_fixed=baselines,
training=dict(positive=int(sum(y == 1)), negative=int(sum(y == 0)), windows=len(train)),
)
def propose(root):
base_propose(root)
original = json.loads((root / "candidates.json").read_text())
policy = json.loads((root / "assembly-policy.json").read_text())
out = []
for a in original["records"]:
rgb = np.asarray(Image.open(root / "data" / (a["id"] + ".png")).convert("RGB"))
z = dict(np.load(root / "data" / (a["id"] + ".npz")))
variants, audit = {}, {}
for mode in ["hard", "retained"]:
cs, log = assemble(a["variants"][mode], rgb, z, policy)
variants[mode + "_off"] = cs[: len(a["variants"][mode])]
variants[mode + "_on"] = cs
audit[mode] = log
out.append(
dict(
id=a["id"],
street=a["street"],
split=a["split"],
variants=variants,
assembly_audit=audit,
)
)
save_new(
root / "assembled-candidates.json",
dict(**timestamp(), records=out, policy_sha256=sha(root / "assembly-policy.json")),
)
print(json.dumps({k: sum(len(a["variants"][k]) for a in out) for k in out[0]["variants"]}))
def train(root):
records = json.loads((root / "assembled-candidates.json").read_text())["records"]
review = json.loads((root / "review-frozen.json").read_text())["records"]
usable = [a for a in records if a["split"] != "heldout"]
result = fit_models(
usable, {a["id"]: review[a["id"]] for a in usable}, [i / 20 for i in range(1, 20)]
)
previous = json.loads(Path("/objectstudy/models-frozen.json").read_text())["models"][
"shape_appearance"
]
result["previous"] = dict(model=previous["model"], threshold=previous["selected"]["threshold"])
result.update(timestamp())
names = [
"assembled-candidates.json",
"review-frozen.json",
"protocol.json",
"assembly-policy.json",
"input-hashes.json",
"object_assembly_study.py",
"object_proposal_study.py",
"paint_observations.py",
"paint_hypothesis_study.py",
"paint_evidence_probe.py",
"layer_common.py",
"fit_scene.py",
]
result["frozen_sha256"] = {name: sha(root / name) for name in names}
save_new(root / "models-frozen.json", result)
print(json.dumps({k: result[k] for k in ["chosen", "training", "validation_fixed"]}))
def evaluate(root):
frozen = json.loads((root / "models-frozen.json").read_text())
for name, digest in frozen["frozen_sha256"].items():
if sha(root / name) != digest:
raise ValueError("Frozen dependency changed: " + name)
for name, digest in json.loads((root / "input-hashes.json").read_text()).items():
if sha(root / name) != digest:
raise ValueError("Frozen input changed: " + name)
records = json.loads((root / "assembled-candidates.json").read_text())["records"]
review = json.loads((root / "review-frozen.json").read_text())["records"]
results = []
for a in records:
sets = {}
for arm in ["off", "on"]:
sets["proposals_" + arm] = a["variants"]["retained_" + arm]
sets["fixed_admission_" + arm] = admitted(a, arm, "fixed_admission")
sets["previous_shape_appearance_" + arm] = admitted(
a, arm, "previous_shape_appearance", **frozen["previous"]
)
for name, info in frozen["models"].items():
selected = info["arms"][arm]["selected"]
sets[name + "_" + arm] = admitted(
a, arm, name, info["model"], selected["threshold"] if selected else 2
)
results.append(
dict(
id=a["id"],
street=a["street"],
split=a["split"],
scores={k: measured(cs, review[a["id"]]) for k, cs in sets.items()},
accepted_ids={k: [c["id"] for c in cs] for k, cs in sets.items()},
)
)
streets = {
s: {
k: pooled([a["scores"][k] for a in results if a["street"] == s])
for k in results[0]["scores"]
}
for s in sorted({a["street"] for a in results})
}
control = {
k: pooled([a["scores"][k] for a in results if a["split"] == "heldout"])
for k in results[0]["scores"]
}
save_new(
root / "results.json",
dict(
**timestamp(),
chosen=frozen["chosen"],
streets=streets,
control=control,
windows=results,
promotion=False,
),
)
print(
json.dumps(
dict(
control=control,
streets={
k: v for k, v in streets.items() if k in ["pokrovka", "sadovaya-karetnaya"]
},
)
)
)
if __name__ == "__main__":
cv2.setNumThreads(3)
{"propose": propose, "train": train, "evaluate": evaluate}[sys.argv[1]](Path(sys.argv[2]))
@@ -0,0 +1,374 @@
"""Offline, frozen object-proposal comparison; never publishes map features.
The production proposal generator is reused. Downstream family fitting and the
full mapping pipeline are deliberately outside this admission-stage experiment.
"""
import hashlib
import json
import sys
import time
from datetime import UTC, datetime
from pathlib import Path
import cv2
import numpy as np
from paint_hypothesis_study import fit_classifier, probability
from paint_observations import collect
from PIL import Image
from scipy.optimize import linear_sum_assignment
from shapely import affinity
from shapely.geometry import Polygon, mapping, shape
from shapely.ops import unary_union
SHAPE = ["area", "length", "width", "aspect", "fill", "solidity", "holes", "compactness"]
APPEARANCE = ["gray_mean", "gray_p10", "saturation", "contrast", "yellow", "white"]
CONTEXT = ["road", "roadway", "sidewalk", "marking", "crosswalk"]
VARIANTS = {"shape": 8, "shape_appearance": 14, "shape_appearance_context": 19}
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def save_new(path, value):
with Path(path).open("x") as f:
json.dump(value, f, indent=2, allow_nan=False)
def timestamp():
return dict(utc=datetime.now(UTC).isoformat(), monotonic=time.monotonic())
def masks(poly, size=512):
mask = np.zeros((size, size), np.uint8)
cv2.fillPoly(mask, [np.rint(poly.exterior.coords).astype(np.int32)], 1)
for hole in poly.interiors:
cv2.fillPoly(mask, [np.rint(hole.coords).astype(np.int32)], 0)
return mask.astype(bool)
def to_pixel(poly):
return affinity.translate(affinity.scale(poly, 512 / 12, -512 / 12, origin=(0, 0)), -0.5, 511.5)
def deduplicate(items):
out = []
for p, props in sorted(items, key=lambda x: (-x[0].area, x[0].wkt)):
if any(p.intersection(q).area / p.union(q).area > 0.85 for q, _ in out):
continue
out.append((p, props))
return out
def descriptors(poly, rgb, fields):
mask = masks(poly)
if not mask.any():
raise ValueError("Empty rasterized candidate")
hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32)
contrast = gray - cv2.GaussianBlur(gray, (0, 0), 0.35 * 512 / 12)
short, long = sorted(cv2.minAreaRect(np.asarray(poly.exterior.coords, np.float32))[1])
area = poly.area
values = [
area * (12 / 512) ** 2,
long * 12 / 512,
short * 12 / 512,
long / max(short, 1e-8),
area / max(short * long, 1e-8),
area / max(poly.convex_hull.area, 1e-8),
len(poly.interiors),
4 * np.pi * area / max(poly.length**2, 1e-8),
gray[mask].mean() / 255,
np.quantile(gray[mask], 0.1) / 255,
hsv[..., 1][mask].mean() / 255,
contrast[mask].mean() / 255,
np.mean(((hsv[..., 0] > 12) & (hsv[..., 0] < 36) & (hsv[..., 1] > 55))[mask]),
np.mean(((hsv[..., 1] < 85) & (gray > 115))[mask]),
]
values.extend(
float(np.mean(fields[k][mask]))
for k in ["road", "roadway", "sidewalk", "road marking", "crosswalk"]
)
return [float(v) for v in values]
def propose(root):
records = json.loads((root / "inputs.json").read_text())["records"]
for name, digest in json.loads((root / "input-hashes.json").read_text()).items():
if sha(root / name) != digest:
raise ValueError("Changed frozen input: " + name)
g = dict(
view=np.array([[1, 0, 0, -6], [0, -1, 0, 6], [0, 0, -1, 10], [0, 0, 0, 1]], float),
intrinsics=np.array([[100, 0, 600], [0, 100, 600], [0, 0, 1]], float),
)
results = []
for a in records:
rgb = np.asarray(Image.open(root / "data" / (a["id"] + ".png")).convert("RGB"))
z = dict(np.load(root / "data" / (a["id"] + ".npz")))
road = cv2.resize(
z["road"].astype(np.uint8), (120, 120), interpolation=cv2.INTER_NEAREST
).astype(bool)
distance = cv2.resize(z["road_dist"].astype(np.float32), (120, 120))
variants = {}
for mode in ["hard", "retained"]:
paint, cross = collect(
rgb,
z["vehicle"],
g,
z["road marking"],
z["crosswalk"],
road,
[0, 0],
[12, 12],
{"id": a["id"]},
distance,
span_m=12,
retain_uncertain=mode == "retained",
valid=z["alpha"],
)
candidates = []
for i, (poly, props) in enumerate(deduplicate(paint + cross)):
pp = to_pixel(poly)
# Fixed comparator stops at candidate admission; no family fitting.
admitted = (
props.get("subtype") == "crosswalk"
or props.get("proposal_contract") == "semantic-paint-v1"
or (
props.get("semantic_support", 0) >= 0.10
and props.get("semantic_peak", 0) >= 0.3
)
)
candidates.append(
dict(
id=f"{mode}-{i}",
geometry=mapping(pp),
properties=props,
features=descriptors(pp, rgb, z),
fixed_admitted=bool(admitted),
)
)
variants[mode] = candidates
results.append(dict(id=a["id"], street=a["street"], split=a["split"], variants=variants))
save_new(
root / "candidates.json",
dict(
**timestamp(),
records=results,
feature_names=SHAPE + APPEARANCE + CONTEXT,
generator_sha256=sha(Path(__file__).with_name("paint_observations.py")),
),
)
print(
json.dumps(
{
"windows": len(results),
"candidates": {
mode: sum(len(a["variants"][mode]) for a in results)
for mode in ["hard", "retained"]
},
}
)
)
def overlap(a, b):
return a.intersection(b).area / max(a.union(b).area, 1e-9)
def labels(candidates, reviewed):
truth = [shape(o["geometry"]) for o in reviewed["objects"]]
negative = unary_union([Polygon(p) for p in reviewed["negative"]])
out = []
for c in candidates:
p = shape(c["geometry"])
best = max([overlap(p, t) for t in truth], default=0)
if best >= 0.5:
out.append(1)
elif not negative.is_empty and p.intersection(negative).area / p.area >= 0.90:
out.append(0)
else:
out.append(-1)
return np.array(out)
def matched(candidates, reviewed, complete=True):
truth = [o for o in reviewed["objects"] if o["complete"] == complete]
ious = np.array(
[[overlap(shape(c["geometry"]), shape(t["geometry"])) for t in truth] for c in candidates]
)
best = np.max(ious, axis=0).tolist() if candidates and truth else [0.0] * len(truth)
found = set()
if candidates and truth:
rows, cols = linear_sum_assignment(-2 * (ious >= 0.5).astype(float) - 0.001 * ious)
found = {int(j) for i, j in zip(rows, cols, strict=True) if ious[i, j] >= 0.5}
return dict(
total=len(truth),
found=len(found),
recall=len(found) / len(truth) if truth else None,
objects=[
dict(id=t["id"], family=t["family"], best_iou=best[i], matched=i in found)
for i, t in enumerate(truth)
],
)
def score(candidates, reviewed):
result = matched(candidates, reviewed)
result["unsupported"] = int(np.sum(labels(candidates, reviewed) == 0))
result["accepted"] = len(candidates)
result["clipped_components"] = matched(candidates, reviewed, complete=False)
return result
def aggregate(rows):
total = sum(r["total"] for r in rows)
found = sum(r["found"] for r in rows)
return dict(
total=total,
found=found,
recall=found / total if total else None,
unsupported=sum(r["unsupported"] for r in rows),
accepted=sum(r["accepted"] for r in rows),
)
def fit_models(records, review, thresholds):
train = [a for a in records if a["split"] == "train"]
val = [a for a in records if a["split"] == "validation"]
baseline = aggregate(
[
score([c for c in a["variants"]["hard"] if c["fixed_admitted"]], review[a["id"]])
for a in val
]
)
x, y = [], []
for a in train:
cs = a["variants"]["retained"]
ls = labels(cs, review[a["id"]])
for c, label in zip(cs, ls, strict=True):
if label >= 0:
x.append(c["features"])
y.append(label)
x, y = np.asarray(x), np.asarray(y)
if min(np.sum(y == 0), np.sum(y == 1)) < 2:
raise ValueError("Insufficient independent training candidates")
models, choices = {}, []
for variant, count in VARIANTS.items():
model = fit_classifier(x[:, :count], y, 0.01, 500)
rows = []
for threshold in thresholds:
scores = []
for a in val:
cs = a["variants"]["retained"]
ps = probability(np.array([c["features"][:count] for c in cs]), model) if cs else []
scores.append(
score(
[c for c, p in zip(cs, ps, strict=True) if p >= threshold], review[a["id"]]
)
)
summary = aggregate(scores)
rows.append(dict(threshold=threshold, **summary))
feasible = [v for v in rows if v["unsupported"] <= baseline["unsupported"]]
selected = (
min(feasible, key=lambda v: (-v["found"], v["unsupported"], v["threshold"]))
if feasible
else None
)
models[variant] = dict(model=model, validation=rows, selected=selected)
if selected:
choices.append(dict(variant=variant, **selected))
chosen = (
min(choices, key=lambda v: (-v["found"], v["unsupported"], v["variant"]))
if choices
else None
)
return dict(
models=models,
chosen=chosen,
baseline_validation=baseline,
training=dict(positive=int(sum(y == 1)), negative=int(sum(y == 0)), windows=len(train)),
)
def train(root):
records = json.loads((root / "candidates.json").read_text())["records"]
review = json.loads((root / "review-frozen.json").read_text())["records"]
# Never pass heldout labels to fitting or selection.
usable = [a for a in records if a["split"] != "heldout"]
limited_review = {a["id"]: review[a["id"]] for a in usable}
protocol = json.loads((root / "protocol.json").read_text())
result = fit_models(usable, limited_review, protocol["fixed_design"]["threshold_grid"])
result.update(timestamp())
result["source_sha256"] = sha(__file__)
result["input_sha256"] = {
n: sha(root / n)
for n in ["candidates.json", "review-frozen.json", "protocol.json", "input-hashes.json"]
}
save_new(root / "models-frozen.json", result)
print(json.dumps({k: result[k] for k in ["chosen", "baseline_validation", "training"]}))
def evaluate(root):
frozen = json.loads((root / "models-frozen.json").read_text())
if frozen["source_sha256"] != sha(__file__):
raise ValueError("Source changed after model freeze")
for name, digest in frozen["input_sha256"].items():
if sha(root / name) != digest:
raise ValueError("Input changed after model freeze: " + name)
records = json.loads((root / "candidates.json").read_text())["records"]
review = json.loads((root / "review-frozen.json").read_text())["records"]
result = []
for a in records:
sets = {
"hard_proposals": a["variants"]["hard"],
"retained_proposals": a["variants"]["retained"],
"fixed_admission": [c for c in a["variants"]["hard"] if c["fixed_admitted"]],
}
for variant, count in VARIANTS.items():
item = frozen["models"][variant]
cs = a["variants"]["retained"]
ps = (
probability(np.array([c["features"][:count] for c in cs]), item["model"])
if cs
else []
)
threshold = item["selected"]["threshold"] if item["selected"] else 2
sets[variant] = [
dict(c, probability=float(p)) for c, p in zip(cs, ps, strict=True) if p >= threshold
]
result.append(
dict(
id=a["id"],
street=a["street"],
split=a["split"],
scores={k: score(cs, review[a["id"]]) for k, cs in sets.items()},
accepted_ids={k: [c["id"] for c in cs] for k, cs in sets.items()},
)
)
streets = {
street: {
mode: aggregate([a["scores"][mode] for a in result if a["street"] == street])
for mode in result[0]["scores"]
}
for street in sorted({a["street"] for a in result})
}
save_new(
root / "results.json",
dict(
**timestamp(),
chosen=frozen["chosen"],
streets=streets,
windows=result,
scope=(
"Object proposal/admission stage only; "
"no downstream fit or full-pipeline acceptance."
),
),
)
print(json.dumps(streets))
if __name__ == "__main__":
cv2.setNumThreads(3)
{"propose": propose, "train": train, "evaluate": evaluate}[sys.argv[1]](Path(sys.argv[2]))
@@ -0,0 +1,206 @@
"""Known-support digital connectivity; caller binds evidence, never full-object topology."""
import hashlib
from collections import deque
import numpy as np
from scipy.ndimage import label
def _sha(array):
return hashlib.sha256(array.tobytes()).hexdigest()
def _path(allowed, start, goal, offsets, budget, origin, max_path):
h, w = allowed.shape
parents = np.full(h * w, -2, np.int32)
seeds = np.flatnonzero(start & allowed)
parents[seeds] = -1
queue = deque(map(int, seeds))
while queue:
if budget[0] <= 0:
raise ValueError("Connectivity work budget exceeded")
budget[0] -= 1
here = queue.popleft()
y, x = divmod(here, w)
if goal[y, x]:
path = []
while here != -1:
y, x = divmod(here, w)
path.append([x + origin[0], y + origin[1]])
if len(path) > max_path:
raise ValueError("Complete witness exceeds path budget")
here = int(parents[here])
return path[::-1]
for dy, dx in offsets:
yy, xx = y + dy, x + dx
if 0 <= yy < h and 0 <= xx < w:
nxt = yy * w + xx
if parents[nxt] == -2 and allowed[yy, xx]:
parents[nxt] = here
queue.append(nxt)
return None
def audit_topology(
probability, target, cores, relations, *, roi, connectivity, max_nodes=1_000_000, max_path=4096
):
"""Native bool cores by ID; relations are {left,right,gap:bool mask}.
Exclusive ROI [x0,y0,x1,y1], fixed >=.5, native integer path centres.
Each known-core CC is independent; no full-object/exterior claim.
Resource refusal returns no partial result or truncated witness.
"""
if (
not isinstance(target, np.ndarray)
or target.ndim != 2
or target.dtype != np.uint8
or not 0 < target.size <= 1_048_576
or not np.isin(target, [0, 1, 255]).all()
):
raise ValueError("Bounded native uint8 0/1/255 target required")
if (
not isinstance(probability, np.ndarray)
or probability.shape != target.shape
or probability.dtype.kind != "f"
or not np.isfinite(probability).all()
or not ((probability >= 0) & (probability <= 1)).all()
):
raise ValueError("Aligned finite probabilities in [0,1] required")
h, w = target.shape
if (
len(roi) != 4
or any(type(v) is not int for v in roi)
or not 0 <= roi[0] < roi[2] <= w
or not 0 <= roi[1] < roi[3] <= h
):
raise ValueError("Exclusive native ROI required")
if type(connectivity) is not int or connectivity not in (4, 8):
raise ValueError("Explicit connectivity 4 or 8 required")
if any(type(v) is not int or not 0 < v <= 1_000_000 for v in (max_nodes, max_path)):
raise ValueError("Positive bounded work/path limits required")
if (
not isinstance(cores, dict)
or not 1 <= len(cores) <= 32
or any(not isinstance(k, str) or not k for k in cores)
or not isinstance(relations, list)
or len(relations) > 32
):
raise ValueError("Bounded named cores/relations required")
x0, y0, x1, y1 = roi
sl = np.s_[y0:y1, x0:x1]
t, pred = target[sl], probability[sl] >= 0.5
if t.size * (3 * len(cores) + 2 * len(relations)) > 64_000_000:
raise ValueError("Array work budget exceeded")
structure = np.ones((3, 3), bool)
if connectivity == 4:
structure[[0, 0, 2, 2], [0, 2, 0, 2]] = False
offsets = [(int(y) - 1, int(x) - 1) for y, x in np.argwhere(structure) if (y, x) != (1, 1)]
budget = [max_nodes]
def mask(value, wanted):
if (
not isinstance(value, np.ndarray)
or value.dtype != bool
or value.shape != target.shape
or np.any(value & (target != wanted))
or int(value.sum()) != int(value[sl].sum())
):
raise ValueError("Mask must match its known class and stay inside ROI")
return value[sl]
def find_path(allowed, start, goal):
return _path(allowed, start, goal, offsets, budget, (x0, y0), max_path)
checked, occupied, objects = {}, np.zeros(t.shape, bool), []
for name, raw in cores.items():
core = mask(raw, 1)
if not core.any() or (occupied & core).any():
raise ValueError("Nonempty disjoint accepted paint cores required")
occupied |= core
checked[name] = core
truth, nt = label(core, structure)
recovered, nr = label(core & pred, structure)
ids = np.unique(truth[core & pred].astype(np.int64) * (nr + 1) + recovered[core & pred])
counts = np.bincount(ids // (nr + 1), minlength=nt + 1)
fragments = np.flatnonzero(counts[1:] > 1) + 1
witness = None
if len(fragments):
component = truth == fragments[0]
rs = np.unique(recovered[component])
rs = rs[rs != 0]
witness = find_path(component, recovered == rs[0], recovered == rs[1])
objects.append(
dict(
id=name,
core_sha256=_sha(raw),
known_pixels=int(core.sum()),
recovered_pixels=int((core & pred).sum()),
original_components=nt,
recovered_components=nr,
fragmented_original_components=len(fragments),
fully_missed_original_components=int((counts[1:] == 0).sum()),
known_core_fragmentation_witness=witness,
touches_roi_edge=bool(
core[0].any() or core[-1].any() or core[:, 0].any() or core[:, -1].any()
),
full_object_split_assessed=False,
)
)
pairs, seen = [], set()
for relation in relations:
left, right = relation["left"], relation["right"]
if left not in checked or right not in checked or left == right:
raise ValueError("Declared distinct core IDs required")
key = tuple(sorted((left, right)))
if key in seen:
raise ValueError("Duplicate relation")
seen.add(key)
gap = mask(relation["gap"], 0)
start, goal = checked[left] & pred, checked[right] & pred
corridor = checked[left] | checked[right] | gap
path = None
if not start.any() or not goal.any():
status = "unassessed_missing_predicted_endpoint"
elif not gap.any():
status = "unassessed_no_known_gap"
else:
path = find_path(pred & corridor, start, goal)
if path is not None:
status = (
"confirmed_known_support_bridge"
if any(gap[y - y0, x - x0] for x, y in path)
else "unassessed_core_adjacency_without_background"
)
else:
path = find_path(pred & (corridor | (t == 255)), start, goal)
status = (
"indeterminate_unknown_connection"
if path is not None
else "no_connection_within_reviewed_corridor"
)
pairs.append(
dict(
left=left,
right=right,
status=status,
witness=path,
gap_pixels=int(gap.sum()),
gap_sha256=_sha(relation["gap"]),
witness_unknown_pixels=int(sum(t[y - y0, x - x0] == 255 for x, y in path or [])),
exterior_connection_assessed=False,
full_object_merge_assessed=False,
)
)
return dict(
schema="missioncore.observed-topology/v1",
threshold=0.5,
connectivity=connectivity,
roi=list(roi),
shape=list(target.shape),
target_sha256=_sha(target),
probability_sha256=_sha(probability),
cores=objects,
relations=pairs,
graph_nodes_visited=max_nodes - budget[0],
semantics="Known-support connectivity only; unassessed is not separation.",
)
@@ -0,0 +1,89 @@
"""Source-local scoring of observed paint; unknown is never ground truth.
Instance polygons only identify observed cores. Gap contamination is not a
merge verdict; uncertainty prevents topology/physical-boundary claims.
"""
import hashlib
import numpy as np
from PIL import Image, ImageDraw
from scipy.spatial import ConvexHull
def array_sha(value):
return hashlib.sha256(value.tobytes()).hexdigest()
def polygon_mask(points, shape):
image = Image.new("1", (shape[1], shape[0]))
ImageDraw.Draw(image).polygon([tuple(p) for p in points], fill=1)
return np.array(image, dtype=bool)
def support(target, instances):
if target.ndim != 2 or target.dtype != np.uint8 or not np.isin(target, [0, 1, 255]).all():
raise ValueError("Native uint8 0/1/255 target required")
cores, gaps, rows = [], [], []
for obj in instances:
core = polygon_mask(obj["outline_native_pixels"], target.shape) & (target == 1)
if int(core.sum()) != obj["final_paint_pixels"] or not core.any():
raise ValueError("Reviewed visible core differs: " + obj["id"])
if any((core & other).any() for other in cores):
raise ValueError("Overlapping instance cores")
cores.append(core)
rows.append(dict(id=obj["id"], visibility=obj["visibility"],
core_pixels=int(core.sum()), core_sha256=array_sha(core)))
if cores and not np.array_equal(np.logical_or.reduce(cores), target == 1):
raise ValueError("Instance observations do not cover exactly the reviewed paint")
# Annotation order is frozen. Only adjacent members of the same crossing
# have a declared between-bars region; partial line fragments do not.
for left, right in zip(instances, instances[1:], strict=False):
if (left["kind"] != "observed_crosswalk_bar"
or right["kind"] != "observed_crosswalk_bar"
or left.get("semantic_group") != right.get("semantic_group")):
continue
pts = np.asarray(left["outline_native_pixels"] + right["outline_native_pixels"])
hull = pts[ConvexHull(pts).vertices]
mask = polygon_mask(hull, target.shape) & (target == 0)
mask &= ~polygon_mask(left["outline_native_pixels"], target.shape)
mask &= ~polygon_mask(right["outline_native_pixels"], target.shape)
gaps.append((dict(pair=[left["id"], right["id"]],
background_pixels=int(mask.sum()), mask_sha256=array_sha(mask)), mask))
return cores, rows, gaps
def score(probability, target, instances):
if (probability.shape != target.shape or not np.isfinite(probability).all()
or not ((probability >= 0) & (probability <= 1)).all()):
raise ValueError("Finite native-grid probabilities required")
pred = probability >= .5
pos, neg = target == 1, target == 0
cores, rows, gaps = support(target, instances)
tp, fn = int((pred & pos).sum()), int((~pred & pos).sum())
fp, tn = int((pred & neg).sum()), int((~pred & neg).sum())
return dict(
prediction_sha256=array_sha(probability), target_sha256=array_sha(target),
tp=tp, fn=fn, fp=fp, tn=tn, paint_pixels=tp+fn, background_pixels=fp+tn,
unknown_pixels=int((target == 255).sum()),
fnr=fn/(tp+fn) if tp+fn else None, fpr=fp/(fp+tn) if fp+tn else None,
observations=[dict(row, tp=int((pred & core).sum()),
fn=int((~pred & core).sum()),
recall=float((pred & core).sum()/core.sum()),
missed_core=not bool((pred & core).any()))
for row, core in zip(rows, cores, strict=True)],
gaps=[dict(row, fp=int((pred & mask).sum()),
fpr=float((pred & mask).sum()/mask.sum()) if mask.any() else None,
assessed=bool(mask.any())) for row, mask in gaps],
not_assessed=["full_window_recall", "whole_crossing_count", "holes",
"physical_boundary_accuracy", "instance_merge_split"],
)
def paired_changes(candidate, baseline, target):
a, b = candidate >= .5, baseline >= .5
if a.shape != target.shape or b.shape != target.shape:
raise ValueError("Paired native shapes differ")
return dict(new_fn=int((~a & b & (target == 1)).sum()),
recovered_fn=int((a & ~b & (target == 1)).sum()),
new_fp=int((a & ~b & (target == 0)).sum()),
removed_fp=int((~a & b & (target == 0)).sum()))
@@ -0,0 +1,279 @@
"""Bounded offline paint-evidence experiment. Never writes production maps.
Training: reviewed weak vector interiors. Evaluation: separately frozen sparse
positive strokes and verified non-paint polygons. This is not a full-map metric.
"""
import hashlib
import json
import time
from datetime import UTC, datetime
from pathlib import Path
import cv2
import numpy as np
from PIL import Image, ImageDraw
from scipy.optimize import minimize
from scipy.special import expit
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def polygon_mask(polygons, size=(512, 512)):
image = Image.new("L", size)
draw = ImageDraw.Draw(image)
for polygon in polygons:
draw.polygon([tuple(p) for p in polygon], fill=255)
return np.array(image) > 0
def probe_masks(record):
image = Image.new("L", (512, 512))
draw = ImageDraw.Draw(image)
for stroke in record["positive"]:
draw.line([tuple(p) for p in stroke], fill=255, width=2)
positive = np.array(image) > 0
negative = polygon_mask(record["negative"])
assert not (positive & negative).any(), "Conflicting review probes"
return positive, negative
def features(rgb):
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)
g = gray.astype(np.float32) / 255
planes = [g, hsv[..., 1] / 255, (rgb[..., 0].astype(float) - rgb[..., 2]) / 255]
names = ["brightness", "saturation", "red_minus_blue"]
for size in [9, 25, 51]:
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (size, size))
planes.append(cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, kernel) / 255)
names.append(f"bright_ridge_{size}px")
avg = cv2.boxFilter(g, -1, (size, size))
planes.append(g - avg)
names.append(f"local_contrast_{size}px")
avg = cv2.boxFilter(g, -1, (9, 9))
planes.append(np.sqrt(np.maximum(0, cv2.boxFilter(g * g, -1, (9, 9)) - avg * avg)))
names.append("local_std_9px")
# Exact pre-morphology predicate from marking_pass.line_reconstruction.extract.
ridge = cv2.morphologyEx(
gray, cv2.MORPH_TOPHAT, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (25, 25))
)
white = (hsv[..., 1] < 100) & (gray > 100)
yellow = (hsv[..., 0] > 12) & (hsv[..., 0] < 36) & (hsv[..., 1] > 50) & (gray > 100)
fixed = (ridge > 12) & (white | yellow)
return np.stack(planes, axis=-1).astype(np.float32), fixed, names
def spatial_rule(mask):
closed = cv2.morphologyEx(mask.astype("uint8"), cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
count, labels, stats, _ = cv2.connectedComponentsWithStats(closed, 8)
eligible = np.zeros(count, bool)
eligible[1:] = stats[1:, cv2.CC_STAT_AREA] >= 12
return eligible[labels]
def counts(prediction, positive, negative):
return dict(
tp=int((prediction & positive).sum()),
fn=int((~prediction & positive).sum()),
fp=int((prediction & negative).sum()),
tn=int((~prediction & negative).sum()),
)
def aggregate(rows):
result = {key: sum(row[key] for row in rows) for key in ["tp", "fn", "fp", "tn"]}
result["recall"] = result["tp"] / max(1, result["tp"] + result["fn"])
result["false_positive_rate"] = result["fp"] / max(1, result["fp"] + result["tn"])
return result
def choose_threshold(rows, grid):
values = []
for threshold in grid:
c = aggregate([counts(p >= threshold, pos, neg) for p, pos, neg in rows])
values.append(dict(threshold=threshold, **c))
accepted = [v for v in values if v["false_positive_rate"] <= 0.01]
best = (
max(accepted, key=lambda v: (v["recall"], -v["false_positive_rate"]))
if accepted
else min(values, key=lambda v: (v["false_positive_rate"], -v["recall"]))
)
return best["threshold"], values
def main(root):
start = time.monotonic()
split = json.loads((root / "split.json").read_text())
review = json.loads((root / "review-frozen.json").read_text())
assert review["reviewed_before_fit"] and not review["human_approved"]
assert not (root / "result.json").exists(), "Immutable first result already exists"
method = review["method"]
rng = np.random.default_rng(method["seed"])
records = split["records"]
assert len({a["id"] for a in records}) == len(records)
for a in records:
assert digest(Path(a["path"]) / "top.png") == a["raw_sha256"]
# All Maroseyka train/validation/test windows are physically nonoverlapping.
local = [a for a in records if "center" in a]
for a in local:
for b in local:
if a["split"] != b["split"]:
assert abs(a["center"][0] - b["center"][0]) >= 28
data = {}
xx, yy, train_counts = [], [], []
for a in records:
rgb = np.array(Image.open(Path(a["path"]) / "top.png").convert("RGB").resize((512, 512)))
f, fixed, names = features(rgb)
data[a["id"]] = dict(rgb=rgb, f=f, fixed=fixed)
if a["split"] != "train":
continue
target = np.array(Image.open(root / "review" / (a["id"] + "-mask.png"))) > 0
roi = polygon_mask([a["roi"]])
positive = cv2.erode(target.astype("uint8"), np.ones((5, 5), np.uint8)) > 0
positive &= roi
excluded = cv2.dilate(target.astype("uint8"), np.ones((15, 15), np.uint8)) > 0
negative = (roi | polygon_mask(review["train_extra_negatives"][a["id"]])) & ~excluded
assert positive.any() and negative.any()
train_counts.append(
dict(id=a["id"], positive=int(positive.sum()), negative=int(negative.sum()))
)
for label, mask in [(1, positive), (0, negative)]:
indices = np.flatnonzero(mask)
indices = rng.choice(
indices,
min(len(indices), method["maximum_samples_per_class_per_window"]),
replace=False,
)
xx.append(f.reshape(-1, f.shape[-1])[indices])
yy.append(np.full(len(indices), label))
x = np.concatenate(xx).astype(float)
y = np.concatenate(yy)
mean, scale = x.mean(axis=0), np.maximum(x.std(axis=0), 1e-5)
design = np.column_stack([np.ones(len(x)), (x - mean) / scale])
weight = np.where(y == 1, 0.5 / max(1, sum(y == 1)), 0.5 / max(1, sum(y == 0)))
l2 = method["l2"]
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
fit_start = time.monotonic()
fit = minimize(
objective,
np.zeros(design.shape[1]),
jac=True,
method="L-BFGS-B",
options={"maxiter": method["maximum_iterations"]},
)
fit_seconds = time.monotonic() - fit_start
assert fit.success, str(fit.message)
validation = []
for a in records:
v = data[a["id"]]
v["probability"] = expit(fit.x[0] + ((v["f"] - mean) / scale) @ fit.x[1:])
if a["split"] == "validation":
pos, neg = probe_masks(review["records"][a["id"]])
validation.append((v["probability"], pos, neg))
threshold, curve = choose_threshold(validation, method["threshold_grid"])
model = dict(
kind="linear-logistic-regression",
names=names,
mean=mean.tolist(),
scale=scale.tolist(),
coefficients=fit.x.tolist(),
threshold=threshold,
seed=method["seed"],
split_sha256=digest(root / "split.json"),
review_sha256=digest(root / "review-frozen.json"),
samples=len(x),
positive_samples=int(y.sum()),
converged=bool(fit.success),
iterations=int(fit.nit),
fit_seconds=fit_seconds,
production_eligible=False,
)
# Publish immutable model before examining held-out metrics.
(root / "fitted-model.json").write_text(json.dumps(model, indent=2))
rows = []
for a in records:
if a["split"] == "train":
continue
v = data[a["id"]]
pos, neg = probe_masks(review["records"][a["id"]])
predictions = dict(
fixed=v["fixed"],
fixed_spatial=spatial_rule(v["fixed"]),
learned=v["probability"] >= threshold,
learned_spatial=spatial_rule(v["probability"] >= threshold),
)
row = dict(
id=a["id"],
split=a["split"],
variants={k: counts(p, pos, neg) for k, p in predictions.items()},
)
rows.append(row)
# Raw frame, fixed predicate, learned predicate, learned + local spatial rule.
sheet = Image.new("RGB", (2048, 550), "#171717")
draw = ImageDraw.Draw(sheet)
for j, key in enumerate(["raw", "fixed", "learned", "learned_spatial"]):
rgb = v["rgb"].copy()
if key != "raw":
pred = predictions[key]
rgb[pred] = (rgb[pred] * 0.35 + np.array([0, 255, 150]) * 0.65).astype("uint8")
sheet.paste(Image.fromarray(rgb), (j * 512, 38))
text = a["id"] + " | " + key
if key != "raw":
c = aggregate([row["variants"][key]])
text += f" R {c['recall']:.1%} FPR {c['false_positive_rate']:.1%}"
draw.text((j * 512 + 5, 10), text, fill="white")
sheet.save(root / (a["id"] + "-result.jpg"), quality=94)
metrics = {}
for split_name in ["validation", "test", "external"]:
metrics[split_name] = {
key: aggregate([row["variants"][key] for row in rows if row["split"] == split_name])
for key in rows[0]["variants"]
}
result = dict(
schema="missioncore.paint-evidence-result/v1",
utc=datetime.now(UTC).isoformat(),
started_monotonic=start,
elapsed_seconds=time.monotonic() - start,
model=model,
train_counts=train_counts,
threshold_validation=curve,
metrics=metrics,
windows=rows,
source_sha256=digest(Path(__file__)),
map_writes=False,
production_eligible=False,
limitations=[
"Sparse assistant-reviewed probes, not dense human-verified benchmark.",
"Fixed comparator is paint-evidence predicate only, not complete production pipeline.",
"Spatial filter is local image morphology, not GOST or topology reconstruction.",
"No object-class recognition, no boundary learning, no full-street completion.",
"Two external windows from historically seen scene; insufficient generalization proof.",
],
)
(root / "result.json").write_text(json.dumps(result, indent=2))
print(
json.dumps(
dict(
metrics=metrics,
threshold=threshold,
fit_seconds=fit_seconds,
samples=len(x),
seconds=result["elapsed_seconds"],
model_sha256=digest(root / "fitted-model.json"),
)
)
)
if __name__ == "__main__":
main(Path("/experiment"))
@@ -0,0 +1,178 @@
"""Exact, offline observed-paint geometry; no inference, fitting or map publication.
Input is a discrete 0=background, 1=paint, 255=unknown grid. Coordinates refer to
pixel EDGES, not centres. A connected component is an observation, not a semantic
instance. Raw geometry remains 2-D until an explicit height provider is supplied.
"""
import copy
import hashlib
import json
import numpy as np
from shapely import affinity, normalize
from shapely.geometry import box, mapping, shape
from shapely.ops import unary_union
SCHEMA = "missioncore.paint-geometry/v1"
MAX_CELLS = 1024 * 1024
MAX_RUNS = 32768
MAX_EDITOR_RINGS = 128
MAX_EDITOR_WORK = 2_000_000
def digest(value):
return hashlib.sha256(
json.dumps(value, sort_keys=True, allow_nan=False, separators=(",", ":")).encode()
).hexdigest()
def _runs(mask):
padded = np.pad(mask.astype(np.int8), ((0, 0), (1, 1)))
rows, starts = np.where(np.diff(padded, axis=1) == 1)
end_rows, ends = np.where(np.diff(padded, axis=1) == -1)
if not np.array_equal(rows, end_rows):
raise ValueError("Unpaired raster runs")
if len(rows) > MAX_RUNS:
raise ValueError("Raster run budget exceeded; no lossy fallback")
return list(zip(rows.tolist(), starts.tolist(), ends.tolist(), strict=True))
def _cells_geometry(runs):
return unary_union([box(start, row, end, row + 1) for row, start, end in runs])
def vectorize(labels, *, pixel_to_scene, source_id):
"""Return a bounded 2-D proposal, with exact cells and explicit unknown support.
pixel_to_scene is Shapely's [a,b,d,e,xoff,yoff] affine: x=a*col+b*row+xoff.
Source identity is caller-owned (tile/revision); the complete label bytes and
transform are additionally bound into the proposal hash.
"""
labels = np.asarray(labels)
matrix = np.asarray(pixel_to_scene, dtype=float)
if (
labels.ndim != 2 or not labels.size or labels.size > MAX_CELLS
or labels.dtype.kind not in "biu" or not np.isin(labels, [0, 1, 255]).all()
):
raise ValueError("Expected bounded integer 0/1/255 grid")
if (
matrix.shape != (6,) or not np.isfinite(matrix).all()
or abs(matrix[0] * matrix[3] - matrix[1] * matrix[2]) < 1e-12
):
raise ValueError("Finite non-singular pixel-edge affine required")
if not isinstance(source_id, str) or not 1 <= len(source_id) <= 256:
raise ValueError("Source identity required")
label_sha = hashlib.sha256(labels.astype(np.uint8).tobytes()).hexdigest()
identity = dict(
source_id=source_id, labels_sha256=label_sha, shape=list(labels.shape),
pixel_to_scene=matrix.tolist(),
)
source_sha = digest(identity)
paint = _cells_geometry(_runs(labels == 1))
unknown = _cells_geometry(_runs(labels == 255))
height, width = labels.shape
edge = box(0, 0, width, height).boundary
polygons = [] if paint.is_empty else (
[paint] if paint.geom_type == "Polygon" else list(paint.geoms)
)
# Zero tolerance only removes collinear run endpoints; assert no area change.
features = []
for poly in polygons:
if poly.geom_type != "Polygon" or not poly.is_valid:
raise ValueError("Unsupported raster topology; no automatic repair")
compact = poly.simplify(0, preserve_topology=True)
if not compact.equals(poly):
raise ValueError("Polygon compaction changed observed paint")
world = normalize(affinity.affine_transform(compact, matrix))
if not world.is_valid or world.is_empty:
raise ValueError("Invalid transformed geometry")
geometry = json.loads(json.dumps(mapping(world)))
flags = []
if poly.intersects(edge):
flags.append("tile-edge")
if not unknown.is_empty and poly.intersects(unknown):
flags.append("unknown-support")
features.append(dict(
type="Feature", id="paint-" + digest([source_sha, geometry])[:24],
geometry=geometry,
properties=dict(
observation_role="observed-paint-component",
source_id=source_id, source_sha256=source_sha,
support_boundary=flags, instance_completeness="not-assessed",
review_status="unreviewed",
),
))
features.sort(key=lambda f: f["id"])
result = dict(
schema_version=SCHEMA, source=identity, source_sha256=source_sha,
counts=dict(paint=int(np.count_nonzero(labels == 1)),
background=int(np.count_nonzero(labels == 0)),
unknown=int(np.count_nonzero(labels == 255))),
features=features,
)
result["proposal_sha256"] = digest(result)
return result
def editor_features(proposal, *, height_at, height_source):
"""Validate and lift exact components, WITHOUT inferring a subtype/template/group.
Caller supplies observed surface heights at the returned XY vertices. There
is no flat/nearest-height fallback. This creates features only: the caller
must independently verify scene identity/admission before any map import.
"""
from k1link.simulation.ai_polygon.semantic_edits import validate_holes, validate_path
payload = {k: v for k, v in proposal.items() if k != "proposal_sha256"}
if proposal.get("schema_version") != SCHEMA or digest(payload) != proposal.get(
"proposal_sha256"
):
raise ValueError("Changed or unsupported geometry proposal")
if not isinstance(height_source, str) or not 1 <= len(height_source) <= 256:
raise ValueError("Explicit height provenance required")
# Existing editor validators have quadratic segment/ring comparisons.
# Budget the WHOLE proposal before any geometry validator or height callback.
work = 0
vertices = 0
if len(proposal["features"]) > 20000:
raise ValueError("Editor feature budget exceeded")
for raw in proposal["features"]:
geo = raw["geometry"]
if geo["type"] != "Polygon":
raise ValueError("Unsupported editor geometry")
rings = geo["coordinates"]
if not rings or len(rings) > MAX_EDITOR_RINGS:
raise ValueError("Editor ring budget exceeded; no lossy fallback")
if any(not 4 <= len(ring) <= 4096 for ring in rings):
raise ValueError("Editor path budget exceeded")
edges = sum(len(ring) - 1 for ring in rings)
vertices += sum(len(ring) for ring in rings)
work += edges * edges
if vertices > 300000 or work > MAX_EDITOR_WORK:
raise ValueError("Editor validation work budget exceeded; no lossy fallback")
result = []
for raw in proposal["features"]:
feature = copy.deepcopy(raw)
geometry = feature["geometry"]
if geometry["type"] != "Polygon" or not shape(geometry).is_valid:
raise ValueError("Unsupported editor geometry")
rings = []
for ring in geometry["coordinates"]:
xy = np.asarray(ring[:-1], dtype=float)
z = np.asarray(height_at(xy.copy()), dtype=float)
if z.shape != (len(xy),) or not np.isfinite(z).all():
raise ValueError("Missing observed height support")
points = np.column_stack([xy, z]).tolist()
points.append(points[0][:])
validate_path(points, True)
rings.append(points)
validate_holes(rings)
feature["geometry"]["coordinates"] = rings
feature["properties"].update({
"class": "road_marking", "authority": "observation-only",
"route_permission": "unassigned", "confidence": None,
"confidence_status": "not-assessed", "annotation_origin": "mask-observation",
"height_source": height_source,
})
result.append(feature)
return result
@@ -0,0 +1,380 @@
"""Frozen factorial diagnostic of photometry, label quality and road context.
Two explicit phases prevent holdout outcomes from selecting thresholds/models.
No production maps, inferred labels, street IDs or coordinates enter the fit.
"""
import argparse
import hashlib
import json
import time
from datetime import UTC, datetime
from pathlib import Path
import cv2
import numpy as np
from paint_evidence_probe import (
aggregate,
choose_threshold,
counts,
features,
polygon_mask,
probe_masks,
)
from PIL import Image, ImageDraw
from scipy.optimize import minimize
from scipy.special import expit
APPEARANCES = ("absolute", "augmented", "relative")
CONTEXTS = ("none", "semantic", "fused")
def sha(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def save_new(path, value):
with path.open("x") as stream:
json.dump(value, stream, indent=2)
def transformed(rgb, kind, value):
if kind == "identity":
return rgb.copy()
x = rgb.astype(np.float32) / 255
x = x * value if kind == "gain" else x**value
return np.rint(np.clip(x, 0, 1) * 255).astype(np.uint8)
def representation(rgb, kind):
f, fixed, names = features(rgb)
if kind != "relative":
return f, fixed, names
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32) / 255
saturation = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)[..., 1] / 255
chroma = (rgb[..., 0].astype(float) - rgb[..., 2]) / np.maximum(
rgb.astype(float).sum(axis=2), 1
)
planes = [saturation, chroma]
names = ["saturation", "normalized_red_blue"]
for index, size in enumerate([9, 25, 51]):
avg = cv2.boxFilter(gray, -1, (size, size))
planes.extend([f[..., 3 + index * 2] / (avg + 0.05), (gray - avg) / (avg + 0.05)])
names.extend([f"relative_ridge_{size}", f"relative_contrast_{size}"])
avg = cv2.boxFilter(gray, -1, (9, 9))
planes.append(f[..., -1] / (avg + 0.05))
names.append("relative_std_9")
return np.stack(planes, axis=-1).astype(np.float32), fixed, names
def fit_classifier(x, y, l2, maxiter):
mean, scale = x.mean(axis=0), np.maximum(x.std(axis=0), 1e-5)
design = np.c_[np.ones(len(x)), (x - mean) / scale]
weights = np.where(y == 1, 0.5 / sum(y == 1), 0.5 / sum(y == 0))
def objective(w):
z = design @ w
loss = np.sum(weights * (np.logaddexp(0, z) - y * z)) + l2 * np.sum(w[1:] ** 2) / 2
grad = design.T @ (weights * (expit(z) - y))
grad[1:] += l2 * w[1:]
return loss, grad
fit = minimize(
objective,
np.zeros(design.shape[1]),
jac=True,
method="L-BFGS-B",
options={"maxiter": maxiter},
)
if not fit.success:
raise RuntimeError(str(fit.message))
return dict(
mean=mean.tolist(),
scale=scale.tolist(),
coefficients=fit.x.tolist(),
iterations=int(fit.nit),
samples=len(y),
)
def probability(f, model):
w = np.array(model["coefficients"])
return expit(w[0] + ((f - np.array(model["mean"])) / np.array(model["scale"])) @ w[1:])
def context(root, record, mode):
if mode == "none":
return np.ones((512, 512), bool)
path = root / "data" / (record["id"] + "-context.npz")
if not path.exists():
return None
with np.load(path) as z:
if mode == "fused":
return z["fused"].astype(bool)
return (z["road"] > 0.35) & (z["road"] >= z["sidewalk"])
def load(root):
for name, digest in json.loads((root / "input-hashes.json").read_text()).items():
if sha(root / name) != digest:
raise ValueError(f"Changed input: {name}")
inputs = json.loads((root / "study-inputs.json").read_text())["records"]
review = json.loads((root / "review-frozen.json").read_text())
prior = json.loads(Path("/prior/review-frozen.json").read_text())
protocol = json.loads((root / "protocol.json").read_text())
return inputs, review, prior, protocol
def rgb(root, record):
return np.array(Image.open(root / "data" / record["raw_file"]).convert("RGB"))
def choose_candidate(rows):
admissible = [a for a in rows if a["false_positive_rate"] <= 0.01]
if admissible:
return sorted(
admissible, key=lambda a: (-a["recall"], a["false_positive_rate"], a["variant"])
)[0]
return sorted(rows, key=lambda a: (a["false_positive_rate"], -a["recall"], a["variant"]))[0]
def train(root):
start = time.monotonic()
records, review, prior, protocol = load(root)
method = protocol["design"]
rng = np.random.default_rng(method["seed"])
sampling, audit = {}, []
for a in records:
if a["split"] != "train":
continue
pos, neg = probe_masks(review["train"][a["id"]])
weak = np.array(Image.open(root / "data" / (a["id"] + "-weak.png"))) > 0
weak = (cv2.erode(weak.astype("uint8"), np.ones((5, 5), np.uint8)) > 0) & polygon_mask(
[a["roi"]]
)
if (weak & neg).any():
raise ValueError("Weak positives conflict with certain negatives")
n = min(2500, int(weak.sum()), int(pos.sum()), int(neg.sum()))
if n < 50:
raise ValueError("Insufficient matched training samples")
sampling[a["id"]] = {
name: rng.choice(np.flatnonzero(mask), n, replace=False)
for name, mask in [("weak", weak), ("reviewed", pos), ("negative", neg)]
}
audit.append(
dict(
id=a["id"],
matched_per_class=n,
weak=int(weak.sum()),
reviewed=int(pos.sum()),
negative=int(neg.sum()),
reviewed_inside_weak=int((pos & weak).sum()),
)
)
models, validation = {}, []
for label in ["weak", "reviewed"]:
for appearance in APPEARANCES:
key = label + "-" + appearance
xx, yy = [], []
for a in records:
if a["split"] != "train":
continue
image = rgb(root, a)
transforms = (
method["augmentation"] if appearance == "augmented" else [["identity", 1]]
)
for kind, value in transforms:
f, _, names = representation(transformed(image, kind, value), appearance)
for target, indices in [
(1, sampling[a["id"]][label]),
(0, sampling[a["id"]]["negative"]),
]:
xx.append(f.reshape(-1, f.shape[-1])[indices])
yy.append(np.full(len(indices), target))
model = fit_classifier(
np.concatenate(xx).astype(float),
np.concatenate(yy),
method["l2"],
method["maxiter"],
)
model.update(appearance=appearance, labels=label, names=names)
rows = []
validation_records = [a for a in records if a["split"] == "validation"]
for a in validation_records:
f, _, _ = representation(rgb(root, a), appearance)
pos, neg = probe_masks(prior["records"][a["id"]])
rows.append((probability(f, model), pos, neg))
model["threshold"], model["validation_curve"] = choose_threshold(
rows, method["threshold_grid"]
)
models[key] = model
for mode in CONTEXTS:
values = [
counts((p >= model["threshold"]) & context(root, a, mode), pos, neg)
for a, (p, pos, neg) in zip(validation_records, rows, strict=True)
]
validation.append(dict(variant=key + "/" + mode, **aggregate(values)))
chosen = choose_candidate(validation)
artifact = dict(
schema="paint-hypothesis-models/v1",
utc=datetime.now(UTC).isoformat(),
monotonic=start,
seconds=time.monotonic() - start,
models=models,
validation=validation,
chosen=chosen,
sampling=audit,
source_sha256=sha(Path(__file__)),
inputs_sha256=sha(root / "input-hashes.json"),
review_sha256=sha(root / "review-frozen.json"),
protocol_sha256=sha(root / "protocol.json"),
production_eligible=False,
)
save_new(root / "models-frozen.json", artifact)
print(
json.dumps(
dict(chosen=chosen, validation=validation, sampling=audit, seconds=artifact["seconds"])
)
)
def evaluate(root):
start = time.monotonic()
records, review, prior, protocol = load(root)
artifact = json.loads((root / "models-frozen.json").read_text())
if artifact["source_sha256"] != sha(Path(__file__)):
raise ValueError("Source changed between fit and evaluation")
models = artifact["models"]
results, stress, gates = [], [], []
chosen_key, chosen_mode = artifact["chosen"]["variant"].split("/")
for a in records:
if a["split"] == "train":
continue
probes = (
review["holdout"][a["id"]] if a["split"] == "holdout" else prior["records"][a["id"]]
)
pos, neg = probe_masks(probes)
image = rgb(root, a)
f, fixed, _ = representation(image, "absolute")
relative, _, _ = representation(image, "relative")
group = a.get("street", a["split"])
masks = {mode: context(root, a, mode) for mode in CONTEXTS}
preds = {"fixed/none": fixed}
for mode in CONTEXTS[1:]:
if masks[mode] is not None:
preds["fixed/" + mode] = fixed & masks[mode]
gates.append(
dict(id=a["id"], group=group, mode=mode, **counts(masks[mode], pos, neg))
)
for key, model in models.items():
predicted = (
probability(relative if model["appearance"] == "relative" else f, model)
>= model["threshold"]
)
for mode in CONTEXTS:
if masks[mode] is not None:
preds[key + "/" + mode] = predicted & masks[mode]
results.append(
dict(
id=a["id"],
group=group,
positive=int(pos.sum()),
negative=int(neg.sum()),
variants={key: counts(value, pos, neg) for key, value in preds.items()},
)
)
# Controlled photometric counterfactuals use identical labels; never tune on them.
if a["split"] in ["test", "external"]:
for kind, value in protocol["design"]["stress"]:
transformed_rgb = transformed(image, kind, value)
fs = {k: representation(transformed_rgb, k)[0] for k in ["absolute", "relative"]}
stress.append(
dict(
id=a["id"],
group=group,
transform=[kind, value],
variants={
key: counts(
probability(
fs["relative" if m["appearance"] == "relative" else "absolute"],
m,
)
>= m["threshold"],
pos,
neg,
)
for key, m in models.items()
},
)
)
if a["id"] in ["sretenka-2", "sadovaya-triumfalnaya-3", "control-05", "tile-59--2"]:
keys = ["raw", "weak-absolute/none", chosen_key + "/none"]
if masks.get(chosen_mode) is not None and chosen_mode != "none":
keys.append(chosen_key + "/" + chosen_mode)
elif masks["fused"] is not None:
keys.append(chosen_key + "/fused")
sheet = Image.new("RGB", (512 * len(keys), 552), "#171717")
draw = ImageDraw.Draw(sheet)
for j, key in enumerate(keys):
im = image.copy()
caption = key
if key != "raw":
pred = preds[key]
im[pred] = (im[pred] * 0.35 + np.array([0, 255, 145]) * 0.65).astype("uint8")
m = aggregate([counts(pred, pos, neg)])
caption += f" R={m['recall']:.1%} FP={m['false_positive_rate']:.1%}"
sheet.paste(Image.fromarray(im), (512 * j, 40))
draw.text((512 * j + 5, 5), a["id"], fill="white")
draw.text((512 * j + 5, 20), caption, fill="white")
sheet.save(root / (a["id"] + "-study.jpg"), quality=95)
metrics = {}
for group in sorted({r["group"] for r in results}):
rows = [r for r in results if r["group"] == group]
keys = set.intersection(*(set(r["variants"]) for r in rows))
metrics[group] = {
key: aggregate([r["variants"][key] for r in rows]) for key in sorted(keys)
}
candidate = {
group: variants.get(artifact["chosen"]["variant"]) for group, variants in metrics.items()
}
qualified = all(
candidate.get(group)
and candidate[group]["recall"] >= 0.95
and candidate[group]["false_positive_rate"] <= 0.02
for group in ["sretenka", "sadovaya-triumfalnaya"]
)
save_new(
root / "evaluation.json",
dict(
utc=datetime.now(UTC).isoformat(),
monotonic=start,
seconds=time.monotonic() - start,
models_sha256=sha(root / "models-frozen.json"),
rows=results,
stress=stress,
gate_rows=gates,
metrics=metrics,
candidate=candidate,
qualifies_sparse_gate=qualified,
production_eligible=False,
),
)
print(
json.dumps(
dict(
candidate=artifact["chosen"]["variant"],
metrics=metrics,
qualifies_sparse_gate=qualified,
seconds=time.monotonic() - start,
)
)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("phase", choices=["train", "evaluate"])
parser.add_argument("--root", type=Path, default=Path("/experiment"))
args = parser.parse_args()
cv2.setNumThreads(1)
(train if args.phase == "train" else evaluate)(args.root)
@@ -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()
@@ -0,0 +1,22 @@
"""Exact D4 training transforms; no RNG, interpolation or new supervision."""
import numpy as np
def permute_training_pair(rgb, target, element):
"""Rotate counterclockwise element%4 times, then reflect if element>=4.
Input must already be a square crop/padded tile. This is training-only:
scene-coordinate metadata is not transformed or exported by this function.
"""
if (type(element) is not int or not 0 <= element < 8
or not isinstance(rgb, np.ndarray) or not isinstance(target, np.ndarray)
or target.ndim != 2 or rgb.shape != (*target.shape, 3)
or not target.shape[0] or target.shape[0] != target.shape[1]
or rgb.dtype != np.uint8 or target.dtype != np.uint8
or not np.isin(target, [0, 1, 255]).all()):
raise ValueError("Square uint8 RGB/0,1,255 target and D4 integer 0..7 required")
image = np.rot90(rgb, element % 4, axes=(0, 1))
labels = np.rot90(target, element % 4, axes=(0, 1))
if element >= 4:
image, labels = image[:, ::-1], labels[:, ::-1]
return image.copy(order="C"), labels.copy(order="C")
@@ -0,0 +1,237 @@
"""Complete reviewed ROI -> existing sparse paint/background/unknown contract.
The explicit background declaration is an annotation decision, not evidence
inferred from a missing polygon. Numeric coverage cannot establish visual truth.
"""
import hashlib
import math
from admission_store import Supervision, pixel_runs, pixel_target
from dataset_store import checksum, confined
def sha(data):
return hashlib.sha256(data).hexdigest()
def runs(data, size, view):
width, height = size
result = dict(view=view, paint=[], background=[], unknown=[])
names = {0: "background", 1: "paint", 255: "unknown"}
for y in range(height):
x = 0
while x < width:
value, start = data[y * width + x], x
while x < width and data[y * width + x] == value:
x += 1
result[names[value]].append([y, start, x])
return result
def roi_bounds(size, roi):
if len(size) != 2 or any(type(v) is not int or not 0 < v <= 2048 for v in size):
raise ValueError("Bounded integer image dimensions required")
if len(roi) != 4 or any(type(v) is not int for v in roi):
raise ValueError("Integer exclusive ROI required")
x0, y0, x1, y1 = roi
if not 0 <= x0 < x1 <= size[0] or not 0 <= y0 < y1 <= size[1]:
raise ValueError("ROI outside source view")
if (x1 - x0) * (y1 - y0) > 65536:
raise ValueError("Review at most 65536 native pixels per unit")
return x0, y0, x1, y1
def polygon_contains(points, x, y):
inside = False
for a, b in zip(points, points[1:] + points[:1], strict=True):
if (a[1] > y) != (b[1] > y) and x < (b[0] - a[0]) * (y - a[1]) / (b[1] - a[1]) + a[0]:
inside = not inside
return inside
def raster_proposal(packet, proposal):
"""Rasterize source-view polygons at pixel centres; uncertain borders ignored."""
size, roi = packet["size"], packet["roi"]
x0, y0, x1, y1 = roi_bounds(size, roi)
if proposal.get("background_reviewed") is not True or not proposal.get("reason", "").strip():
raise ValueError("Explicit whole-ROI background review required")
margin = proposal["boundary_ignore_px"]
if type(margin) is not int or not 1 <= margin <= 4:
raise ValueError("Native-pixel uncertainty margin required")
shapes = proposal["paint_polygons"]
unknown = proposal["unknown_polygons"]
if not 1 <= len(shapes) <= 32 or len(unknown) > 32:
raise ValueError("Bounded visible-paint polygons required")
for points in shapes + unknown:
if not 3 <= len(points) <= 64 or any(
len(p) != 2
or any(type(v) not in (int, float) or not math.isfinite(v) for v in p)
or not x0 <= p[0] <= x1
or not y0 <= p[1] <= y1
for p in points
):
raise ValueError("Polygon outside pinned ROI")
if unknown and not proposal.get("unknown_reason", "").strip():
raise ValueError("Explain uncertain source regions")
width = size[0]
data = bytearray([255]) * (width * size[1])
for y in range(y0, y1):
for x in range(x0, x1):
data[y * width + x] = int(any(polygon_contains(p, x + 0.5, y + 0.5) for p in shapes))
output = data.copy()
explicit_unknown = bytearray(len(data))
for y in range(y0, y1):
for x in range(x0, x1):
i = y * width + x
ambiguous = any(polygon_contains(p, x + 0.5, y + 0.5) for p in unknown)
if ambiguous:
explicit_unknown[i] = 255
for yy in range(max(y0, y - margin), min(y1, y + margin + 1)):
if ambiguous:
break
ambiguous = any(
data[yy * width + xx] != data[i]
for xx in range(max(x0, x - margin), min(x1, x + margin + 1))
)
if ambiguous:
output[i] = 255
record = runs(output, size, packet["view"])
# Outside ROI is not part of the review, even though both use ignore=255.
record["unknown"] = [
[y, max(a, x0), min(b, x1)]
for y, a, b in record["unknown"]
if y0 <= y < y1 and max(a, x0) < min(b, x1)
]
# Keep explicit source uncertainty distinct from automatic edge margins.
record["source_unknown"] = runs(explicit_unknown, size, packet["view"])["unknown"]
return record
def merge(packet, record, original, protected=b""):
"""Require explicit complete ROI, preserve existing labels and protected unknown."""
size, roi = packet["size"], packet["roi"]
x0, y0, x1, y1 = roi_bounds(size, roi)
width, height = size
if (
len(original) != width * height
or set(original) - {0, 1, 255}
or sha(original) != packet["target_sha256"]
):
raise ValueError("Pinned labels changed")
if protected and (len(protected) != len(original) or set(protected) - {0, 1}):
raise ValueError("Aligned protected unknown required")
if protected and any(p and old != 255 for p, old in zip(protected, original, strict=True)):
raise ValueError("Protected mask must contain only unknown labels")
if packet.get("protected_sha256") != sha(protected):
raise ValueError("Protected unknown identity changed")
if record["view"] != packet["view"]:
raise ValueError("Source view mismatch")
checked = pixel_runs(record, size)
covered = set()
for spans in checked.values():
for y, a, b in spans:
if not y0 <= y < y1 or not x0 <= a < b <= x1:
raise ValueError("Labels outside reviewed ROI")
covered.update(range(y * width + a, y * width + b))
if len(covered) != (x1 - x0) * (y1 - y0):
raise ValueError("Incomplete ROI: missing pixels are not background")
candidate = pixel_target(dict(size=size, **record))
source_unknown = pixel_runs(
dict(paint=[], background=[], unknown=record.get("source_unknown", [])), size
)["unknown"]
for y, a, b in source_unknown:
if not y0 <= y < y1 or not x0 <= a < b <= x1:
raise ValueError("Source uncertainty outside reviewed ROI")
for i in range(y * width + a, y * width + b):
if candidate[i] != 255:
raise ValueError("Source uncertainty must be excluded from labels")
if original[i] != 255:
raise ValueError(
"Explicit source uncertainty conflicts with accepted labels; "
"review a separate baseline revision before publication"
)
output, counts = bytearray(original), {"paint": 0, "background": 0, "unknown": 0}
added = {"paint": 0, "background": 0}
for i in covered:
value, old = candidate[i], original[i]
if value != 255 and old != 255 and old != value:
raise ValueError("Proposal conflicts with accepted labels")
if protected and protected[i] and value != 255:
raise ValueError("Proposal fills protected unknown")
if value != 255:
output[i] = value
counts[{0: "background", 1: "paint", 255: "unknown"}[value]] += 1
if old == 255 and value != 255:
added[{0: "background", 1: "paint"}[value]] += 1
return bytes(output), dict(
roi_pixels=len(covered),
coverage=counts,
added=added,
original_sha256=sha(original),
merged_sha256=sha(output),
)
def validate_packet(store, unit):
"""Resolve TRAIN identity from immutable corpus, never trust declared split."""
p = unit["payload"]
if set(p) != {
"supervision",
"sample_id",
"view",
"size",
"roi",
"target_sha256",
"protected_sha256",
}:
raise ValueError("Pinned region packet required")
roi_bounds(p["size"], p["roi"])
pointer = p["supervision"]
with Supervision(store, pointer["path"], pointer["sha256"]) as reader:
reference = reader.corpus.reference(p["sample_id"])
if (
reference["split"] != "train"
or unit["split"] != reference["split"]
or unit["physical_group"] != reference["physical_group"]
):
raise ValueError("Unit disagrees with frozen physical split")
entry = next(
(
e
for b in reader.training_batches("observed_paint")
for e in b
if e["sample_id"] == p["sample_id"]
),
None,
)
if entry is None:
raise ValueError("Sample is not admitted TRAIN")
view = next(
v
for v in entry["inputs"]
if v["sample_id"] == p["sample_id"] and v["view"] == p["view"]
)
target = next(t for t in entry["targets"] if t["view"] == p["view"])
if target["size"] != p["size"] or sha(pixel_target(target)) != p["target_sha256"]:
raise ValueError("Packet target differs from immutable supervision")
# Explicitly excluded pixels are protected; unreviewed complement is not.
protected = bytearray(p["size"][0] * p["size"][1]) if target["unknown"] else b""
for y, a, b in target["unknown"]:
protected[y * p["size"][0] + a : y * p["size"][0] + b] = bytes([1]) * (b - a)
if sha(protected) != p["protected_sha256"]:
raise ValueError("Packet omits protected unknown")
required = {
str(confined(store, reference["dataset"]) / v["name"])
for v in (view["rgb"], view["cameras_member"])
}
required.add(str(reader.root / "supervision.json"))
required.add(str(reader.root / reader.manifest["records"][p["sample_id"]]["path"]))
provided = {str(confined(store, pin["path"])) for pin in unit["sources"]}
if not required.issubset(provided):
raise ValueError("Packet does not pin source camera, image and decision")
if (
checksum(confined(store, reference["dataset"]) / view["rgb"]["name"])
!= view["rgb"]["sha256"]
):
raise ValueError("Raw source changed")
@@ -0,0 +1,188 @@
"""Read-only research proposals -> bounded root decision, never executable work.
The active root session supplies identities and verifies facts. This validates
artifact structure/provenance, not truth or authentication. It neither schedules
agents nor mutates the annotation queue, source labels, models or infrastructure.
"""
import argparse
import json
from pathlib import Path
from urllib.parse import urlparse
from dataset_store import checksum, confined, digest, write
SCHEMA = "missioncore.semantic-research/v1"
MAX_BYTES = 32 * 1024
def bounded(value):
if len(json.dumps(value, ensure_ascii=False, allow_nan=False).encode()) > MAX_BYTES:
raise ValueError("Research artifact byte limit exceeded")
return value
def keys(value, fields):
if not isinstance(value, dict) or set(value) != set(fields.split()):
raise ValueError("Unexpected research fields")
def text(value):
if not isinstance(value, str) or not value.strip() or len(value) > 4000:
raise ValueError("Bounded nonempty explanation required")
def review_research(workspace, brief, report, decision):
for value in (brief, report, decision):
bounded(value)
keys(brief, "schema_version root_actor scout_actor trigger question baseline")
if brief["schema_version"] != SCHEMA:
raise ValueError("Unsupported research schema")
for field in ("root_actor", "scout_actor", "question"):
text(brief[field])
if brief["root_actor"] == brief["scout_actor"]:
raise ValueError("Scout cannot be root decision maker")
if brief["trigger"] not in {"user_request", "new_class", "stagnation", "cost_regression"}:
raise ValueError("An explicit research trigger is required")
keys(brief["baseline"], "path sha256")
baseline = confined(Path(workspace).resolve(), brief["baseline"]["path"])
if not baseline.is_file() or baseline.stat().st_size > MAX_BYTES:
raise ValueError("Bounded existing baseline evidence required")
if checksum(baseline) != brief["baseline"]["sha256"]:
raise ValueError("Baseline evidence changed")
keys(report, "brief_sha256 baseline_option sources ideas unknowns recommendation")
if report["brief_sha256"] != digest(brief):
raise ValueError("Research answered a different brief")
for field in ("baseline_option", "unknowns", "recommendation"):
text(report[field])
if not isinstance(report["sources"], list) or len(report["sources"]) > 6:
raise ValueError("Research source budget exceeded")
sources = {}
for source in report["sources"]:
keys(source, "id title url kind checked_utc supports limitations")
for field in source:
text(source[field])
url = urlparse(source["url"])
if url.scheme != "https" or not url.hostname or url.username or url.password:
raise ValueError("Public HTTPS citation required")
if source["kind"] not in {"official_docs", "official_repo", "paper"}:
raise ValueError("Primary sources required")
if source["id"] in sources:
raise ValueError("Duplicate source")
sources[source["id"]] = source
if not isinstance(report["ideas"], list) or len(report["ideas"]) > 3:
raise ValueError("At most three research ideas")
ideas = {}
for idea in report["ideas"]:
keys(
idea,
"id title basis source_ids evidence hypothesis minimal_test "
"success failure cost risks not_applicable",
)
for field in set(idea) - {"source_ids"}:
text(idea[field])
refs = idea["source_ids"]
if (
not isinstance(refs, list)
or len(set(refs)) != len(refs)
or not set(refs).issubset(sources)
):
raise ValueError("Idea has unbound citations")
if idea["basis"] not in {"local_baseline", "external"} or (
idea["basis"] == "external" and not refs
):
raise ValueError("External idea needs evidence; baseline uses the pinned local result")
if idea["id"] in ideas:
raise ValueError("Duplicate idea")
ideas[idea["id"]] = idea
keys(decision, "actor report_sha256 source_checks verdicts test_plan")
if decision["actor"] != brief["root_actor"]:
raise ValueError("Only assigned root may decide")
if decision["report_sha256"] != digest(report):
raise ValueError("Stale root research review")
checks = decision["source_checks"]
if (
not isinstance(checks, list)
or len(set(checks)) != len(checks)
or not set(checks).issubset(sources)
):
raise ValueError("Unknown root source checks")
seen, selected = set(), []
for verdict in decision["verdicts"]:
keys(verdict, "idea_id outcome reason revisit_when")
idea_id = verdict["idea_id"]
if idea_id not in ideas or idea_id in seen:
raise ValueError("Every verdict needs one known idea")
seen.add(idea_id)
if verdict["outcome"] not in {"test", "defer", "reject"}:
raise ValueError("Root must test, defer or reject")
text(verdict["reason"])
text(verdict["revisit_when"])
if verdict["outcome"] == "test":
if not set(ideas[idea_id]["source_ids"]).issubset(checks):
raise ValueError("Root must verify a selected idea's source claims")
selected.append(idea_id)
if seen != set(ideas) or len(selected) > 1:
raise ValueError("Decide every idea and select at most one cheap test")
plan = decision["test_plan"]
if not selected:
if plan is not None:
raise ValueError("No test was selected")
else:
keys(plan, "idea_id control data_selection metric success failure budget")
if plan["idea_id"] != selected[0]:
raise ValueError("Test is not the root-selected idea")
for field in ("control", "data_selection", "metric", "success", "failure"):
text(plan[field])
keys(plan["budget"], "max_units max_dispatches max_wall_seconds gpu_training_runs")
for field, cap in (("max_units", 8), ("max_dispatches", 16), ("max_wall_seconds", 3600)):
value = plan["budget"][field]
if type(value) is not int or not 1 <= value <= cap:
raise ValueError("Cheap experiment draft budget exceeded")
if (
type(plan["budget"]["gpu_training_runs"]) is not int
or plan["budget"]["gpu_training_runs"] != 0
):
raise ValueError("Research cannot authorize training")
return bounded(
dict(
schema_version=SCHEMA,
brief_sha256=digest(brief),
report_sha256=digest(report),
decision_sha256=digest(decision),
selected_idea=selected[0] if selected else None,
next_action="freeze_separate_experiment" if selected else "keep_current_workflow",
execution_authorized=False,
training_authorized=False,
map_write_authorized=False,
verdicts=decision["verdicts"],
draft_test=plan,
)
)
def load(path):
path = Path(path)
if path.stat().st_size > MAX_BYTES:
raise ValueError("Research input exceeds byte limit")
return json.loads(path.read_text(encoding="utf-8"))
def main():
parser = argparse.ArgumentParser(description=__doc__)
for field in ("workspace", "brief", "report", "decision", "output"):
parser.add_argument("--" + field, required=True)
args = parser.parse_args()
result = review_research(
args.workspace, load(args.brief), load(args.report), load(args.decision)
)
output = Path(args.output)
if output.exists() and load(output) != result:
raise ValueError("Research decision artifact already exists with different content")
if not output.exists():
write(output, result)
print(json.dumps(result, ensure_ascii=False))
if __name__ == "__main__":
main()
@@ -0,0 +1,136 @@
"""Lazy RGB/observed-paint input over the existing pinned Supervision reader.
This is a data adapter, not a trainer, admission policy or model-specific dataset.
It decodes only the current image, never builds C4 caches or copies a dataset.
"""
import copy
import hashlib
import numpy as np
from admission_store import dimensions, pixel_target
from PIL import Image
SPLITS = {"train", "validation", "test", "regression"}
def load_frame(reader, example, view, *, split):
"""Read one raw RGB view and its exact 0/1/255 target from a verified reader."""
if (
split not in SPLITS or example["split"] != split
or example["task"] != "observed_paint"
or example["training_eligible"] is not (split == "train")
or example["background_from_absence"] is not False
):
raise ValueError("Explicit observed-paint split required")
reference = reader.corpus.reference(example["sample_id"])
if any(reference[key] != example[key] for key in ("split", "source", "physical_group")):
raise ValueError("Example does not match pinned source split/group")
selected = [v for v in example["inputs"]
if v["sample_id"] == example["sample_id"] and v["view"] == view]
targets = [v for v in example["targets"] if v["view"] == view]
if len(selected) != 1 or len(targets) != 1:
raise ValueError("Exactly one aligned anchor view and target required")
selected, target = selected[0], targets[0]
size = dimensions(selected["camera"]["size"])
if target["size"] != size or target.get("ignore_index") != 255:
raise ValueError("Target/image alignment or ignore convention changed")
mask = np.frombuffer(pixel_target(target), dtype=np.uint8).reshape(size[1], size[0])
if not np.any(mask != 255):
return None
# open_image verifies source RGB bytes; dimensions checked before decode.
with reader.open_image(selected) as stream, Image.open(stream) as image:
if image.format != "PNG" or image.mode != "RGB" or list(image.size) != size:
raise ValueError("Expected aligned native RGB PNG")
rgb = np.array(image, dtype=np.uint8, copy=True)
return dict(
img=rgb, target=mask,
metadata=dict(
sample_id=example["sample_id"], view=view, split=split,
physical_group=example["physical_group"], source=copy.deepcopy(example["source"]),
review_sha256=example["review_sha256"], input=copy.deepcopy(selected),
target_sha256=hashlib.sha256(mask.tobytes()).hexdigest(),
color_order="RGB", ignore_index=255, background_from_absence=False,
),
)
def training_frames(reader):
"""Use only the reader's TRAIN API; context images are never implicit targets."""
for batch in reader.training_batches("observed_paint", batch_size=1):
for example in batch:
for target in example["targets"]:
frame = load_frame(reader, example, target["view"], split="train")
if frame is not None:
yield frame
def evaluation_frames(reader, *, split):
if split not in {"validation", "test", "regression"}:
raise ValueError("Explicit non-training evaluation split required")
for batch in reader.batches("observed_paint", split, batch_size=1):
for example in batch:
for target in example["targets"]:
frame = load_frame(reader, example, target["view"], split=split)
if frame is not None:
yield frame
def crop(frame, *, left, top, size=512):
"""Native-resolution square; pad unknown; keep exact crop-to-source mapping.
Returns None for a crop with no reviewed supervision. The caller must not
retry indefinitely or pass an all-ignore batch to the loss. This function
does not choose a sampling distribution, augment, rescale or alter cameras.
"""
if "crop_to_source_edges" in frame["metadata"]:
raise ValueError("Nested crop is unsupported; use the native source frame")
rgb, target = frame["img"], frame["target"]
if (
rgb.dtype != np.uint8 or target.dtype != np.uint8 or target.ndim != 2
or rgb.shape != (*target.shape, 3) or not np.isin(target, [0, 1, 255]).all()
):
raise ValueError("Aligned native RGB and 0/1/255 target required")
h, w = target.shape
if (
any(type(v) is not int for v in (left, top, size))
or not 0 <= left < w or not 0 <= top < h or not 1 <= size <= 1024
):
raise ValueError("Invalid bounded crop")
width, height = min(size, w - left), min(size, h - top)
labels = target[top:top + height, left:left + width]
if not np.any(labels != 255):
return None
out = np.full((size, size), 255, np.uint8)
out[:height, :width] = labels
image = np.zeros((size, size, 3), np.uint8)
image[:height, :width] = rgb[top:top + height, left:left + width]
metadata = copy.deepcopy(frame["metadata"])
metadata.update(
crop_to_source_edges=[1, 0, 0, 1, left, top],
source_window=[left, top, left + width, top + height],
native_crop_size=[width, height], padded_size=[size, size],
known_pixels=int(np.count_nonzero(out != 255)),
)
return dict(img=image, target=out, metadata=metadata)
def mmseg_overrides():
"""Model/data numeric contract ONLY; not an installed/runnable MMSeg config.
Raw frames are RGB already. Unknown must remain 255, including padding.
Upstream CE otherwise averages over ignored pixels as well by default.
"""
return dict(
model=dict(
data_preprocessor=dict(
bgr_to_rgb=False, rgb_to_bgr=False, seg_pad_val=255,
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375],
),
decode_head=dict(
num_classes=2, out_channels=2, ignore_index=255,
loss_decode=dict(type="CrossEntropyLoss", use_sigmoid=False,
loss_weight=1., avg_non_ignore=True),
),
),
dataset=dict(reduce_zero_label=False, ignore_index=255),
)
@@ -0,0 +1,128 @@
"""Offline paired ranking diagnosis. Oracle thresholds are never deployment policy."""
import numpy as np
def curve(scores, positives, negatives):
scores = np.asarray(scores)
if scores.ndim != 1 or not np.isfinite(scores).all() or not len(scores):
raise ValueError("Finite nonempty score vector required")
masks = dict(positives, **negatives)
if not positives or not negatives or len(masks) != len(positives) + len(negatives):
raise ValueError("Distinct positive and negative cohort names required")
for mask in masks.values():
if mask.dtype != bool or mask.shape != scores.shape:
raise ValueError("Aligned boolean cohort masks required")
fg = np.logical_or.reduce(list(positives.values()))
bg = np.zeros_like(fg)
for mask in negatives.values():
if np.any(mask & (fg | bg)):
raise ValueError("Negative cohorts must be disjoint from paint and each other")
bg |= mask
known = fg | bg
if not known.any():
raise ValueError("No reviewed support")
idx = np.flatnonzero(known)
idx = idx[np.argsort(-scores[idx], kind="stable")]
sorted_scores = scores[idx]
ends = np.r_[np.flatnonzero(sorted_scores[:-1] != sorted_scores[1:]), len(idx) - 1]
return {
"thresholds": np.r_[np.inf, sorted_scores[ends].astype(np.float64)],
"counts": {k: np.r_[0, np.cumsum(m[idx], dtype=np.int64)[ends]] for k, m in masks.items()},
"support": {k: int(m.sum()) for k, m in masks.items()},
"positive_names": list(positives),
"negative_names": list(negatives),
}
def point(c, index):
t = float(c["thresholds"][index])
return dict(
threshold=None if np.isinf(t) else t,
counts={k: int(v[index]) for k, v in c["counts"].items()},
rates={
k: float(v[index] / c["support"][k]) if c["support"][k] else None
for k, v in c["counts"].items()
},
)
def at_threshold(c, threshold):
if not np.isfinite(threshold):
raise ValueError("Finite threshold required")
return point(c, int(np.flatnonzero(c["thresholds"] >= threshold)[-1]))
def matched(c, budgets):
if set(budgets) != set(c["negative_names"]):
raise ValueError("One explicit budget for every negative cohort required")
valid = np.ones(len(c["thresholds"]), dtype=bool)
for name, budget in budgets.items():
if (
isinstance(budget, bool)
or not isinstance(budget, (int, np.integer))
or not 0 <= budget <= c["support"][name]
):
raise ValueError("Integer false-positive budgets within support required")
valid &= c["counts"][name] <= budget
return point(c, int(np.flatnonzero(valid)[-1]))
def ranking(
c,
positive,
negative_names,
grid=(0, 0.0001, 0.0005, 0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 1),
):
tp = c["counts"][positive]
fp = sum(c["counts"][n] for n in negative_names)
npos = c["support"][positive]
nneg = sum(c["support"][n] for n in negative_names)
if not npos or not nneg:
return dict(positives=npos, negatives=nneg, ap=None, auc=None, points=[])
recall = tp / npos
fpr = fp / nneg
precision = np.divide(tp, tp + fp, out=np.ones(len(tp), dtype=float), where=tp + fp > 0)
ap = float(np.sum(np.diff(recall) * precision[1:]))
auc = float(np.sum(np.diff(fpr) * (recall[1:] + recall[:-1]) * 0.5))
points = []
for rate in grid:
budget = int(np.floor(rate * nneg))
i = int(np.flatnonzero(fp <= budget)[-1])
points.append(
dict(
budget=budget,
fp=int(fp[i]),
tp=int(tp[i]),
precision=float(precision[i]),
recall=float(recall[i]),
)
)
return dict(positives=npos, negatives=nneg, ap=ap, auc=auc, points=points)
def paired(old, new, positives, negatives):
if np.shape(old) != np.shape(new):
raise ValueError("Paired score shapes differ")
curves = {k: curve(s, positives, negatives) for k, s in [("old", old), ("new", new)]}
assert curves["old"]["support"] == curves["new"]["support"]
fixed = {k: at_threshold(c, 0) for k, c in curves.items()}
budgets = {k: fixed["old"]["counts"][k] for k in negatives}
oracle = {k: matched(c, budgets) for k, c in curves.items()}
summaries = {}
for origin, c in curves.items():
summaries[origin] = {}
for name in positives:
summaries[origin][name] = {}
for part, names in [(k, [k]) for k in negatives] + [("combined", list(negatives))]:
summary = ranking(c, name, names)
if name not in ["overall", "weak"] or part != "combined":
summary.pop("points")
summaries[origin][name][part] = summary
return dict(
support=curves["old"]["support"],
fixed=fixed,
budgets=budgets,
oracle=oracle,
ranking=summaries,
)
@@ -0,0 +1,495 @@
"""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)
@@ -0,0 +1,364 @@
"""Bounded train-street development selection; exposed controls evaluated once afterwards.
No coordinates, street identity or hand-coded geometry enters the classifier.
Unknown pixels stay unknown. Every fold excludes a physical area from sampling,
normalization and fitting. The immutable admission split is not rewritten.
"""
import argparse
import json
import time
from pathlib import Path
import numpy as np
from nonlinear_head_probe import fit_mlp, mlp_logits
from pixel_growth_probe import aggregate, counts, fit
from supervision_density_probe import samples
def folds(records):
train = [r for r in records if r["split"] == "train"]
if len({r["sample_id"] for r in records}) != len(records):
raise ValueError("Duplicate sample")
groups = sorted({r["group"] for r in train})
if len(groups) < 3:
raise ValueError("At least three training streets required")
for group in groups:
held = [r for r in train if r["group"] == group]
learn = [r for r in train if r["group"] != group]
if {r["input"]["rgb"]["sha256"] for r in held} & {
r["input"]["rgb"]["sha256"] for r in learn
}:
raise ValueError("Identical RGB across folds")
yield group, learn, held
def select_candidate(rows, baseline):
"""No control inputs accepted; macro BER, with a worst-street guard."""
if not rows or any(r["phase"] != "development" for r in rows):
raise ValueError("Development results only")
candidates = sorted({r["candidate"] for r in rows})
all_groups = {r["held_out"] for r in rows}
if len(all_groups) < 3:
raise ValueError("Incomplete development streets")
summaries = {}
for candidate in candidates:
rr = [r for r in rows if r["candidate"] == candidate]
if len(rr) != len(all_groups) or {r["held_out"] for r in rr} != all_groups:
raise ValueError("Missing or duplicate fold")
errors = []
for r in rr:
m = r["metrics"]
if m["recall"] is None or m["fpr"] is None:
raise ValueError("Both classes required per development street")
errors.append((1 - m["recall"] + m["fpr"]) / 2)
summaries[candidate] = dict(
macro_ber=float(np.mean(errors)),
worst_ber=max(errors),
converged=all(r["converged"] for r in rr),
)
base = summaries[baseline]
if not base["converged"]:
raise ValueError("Reference fit failed")
eligible = [
c
for c in candidates
if summaries[c]["converged"]
and summaries[c]["macro_ber"] < base["macro_ber"] - 1e-12
and summaries[c]["worst_ber"] <= base["worst_ber"] + 1e-12
]
winner = (
min(eligible, key=lambda c: (summaries[c]["macro_ber"], summaries[c]["worst_ber"], c))
if eligible
else baseline
)
return dict(
selected=winner,
development_improved=bool(eligible),
summaries=summaries,
rule="lower macro BER; worst-street BER not higher; rank macro, worst, id",
)
def features(z, representation):
if representation == "semantic":
return z["features"].astype("float32")
if representation == "detail":
return z["detail"].astype("float32")
if representation == "combined":
return np.concatenate([z["features"], z["detail"]], axis=0).astype("float32")
raise ValueError("Unknown representation")
def feature_pixels(f, size, indices):
import torch
h, w = size
y, x = np.unravel_index(indices, (h, w))
grid = np.stack([2 * (x + 0.5) / w - 1, 2 * (y + 0.5) / h - 1], -1).astype("float32")
return 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()
def predict(f, size, indices, model, chunk=8192):
result = np.empty(len(indices), dtype=bool)
for lo in range(0, len(indices), chunk):
x = feature_pixels(f, size, indices[lo : lo + chunk])
if model["head"] == "linear":
m = model["parameters"]
coef = np.asarray(m["coefficients"])
scaled = coef[1:] / np.asarray(m["scale"])
z = x @ scaled + coef[0] - np.asarray(m["mean"]) @ scaled
else:
z = mlp_logits(x, model["parameters"])
result[lo : lo + chunk] = z >= 0
return result
def fit_candidate(units, candidate, held_out=None):
if held_out is not None and any(u["group"] == held_out for u in units):
raise ValueError("Held-out street entered fitting")
if candidate["head"] == "linear":
p = fit(units, candidate["l2"], 500)
p["converged"] = True
else:
p = fit_mlp(units, hidden=32, seed=20261023, l2=candidate["l2"], max_iterations=500)
return dict(candidate=candidate, head=candidate["head"], parameters=p)
def setup(root):
from dataset_store import checksum, read
protocol = read(root / "protocol.json")
frozen = read(root / "review-frozen.json")
manifest = read(root / "feature-manifest.json")
assert (
frozen["protocol_sha256"] == manifest["protocol_sha256"] == checksum(root / "protocol.json")
)
assert frozen["source_sha256"] == checksum(Path(__file__))
assert frozen["supervision"] == manifest["supervision"]
for name, sha in frozen["sources"].items():
assert checksum(root / name) == sha
for r in manifest["records"]:
assert checksum(root / r["cache"]) == r["sha256"]
return protocol, manifest["records"]
def development(root):
import torch
from dataset_store import checksum, write
torch.set_num_threads(3)
start = time.monotonic()
protocol, records = setup(root)
assert not (root / "development-selection.json").exists()
units = {k: [] for k in ["semantic", "detail", "combined"]}
for r in records:
if r["split"] != "train":
continue
with np.load(root / r["cache"]) as z:
for representation in units:
units[representation].append(
samples(features(z, representation), z["target"], r, protocol["fit"])
)
rows = []
(root / "models").mkdir(exist_ok=False)
for fi, (held_out, learn, held) in enumerate(folds(records)):
for candidate in protocol["candidates"]:
started = time.monotonic()
fitting = [u for u in units[candidate["representation"]] if u["group"] != held_out]
assert {u["name"] for u in fitting} == {r["name"] for r in learn}
model = fit_candidate(fitting, candidate, held_out)
mp = root / "models" / ("fold" + str(fi) + "-" + candidate["id"] + ".json")
write(mp, model)
metrics = []
for r in held:
with np.load(root / r["cache"]) as z:
target = z["target"]
indices = np.flatnonzero(target != 255)
pred = predict(
features(z, candidate["representation"]), target.shape, indices, model
)
c = counts(pred, target.ravel()[indices])
c["ignored"] = int((target == 255).sum())
metrics.append(dict(name=r["name"], **c))
rows.append(
dict(
phase="development",
candidate=candidate["id"],
held_out=held_out,
fitted_groups=model["parameters"]["training_groups"],
model_path=mp.relative_to(root).as_posix(),
model_sha256=checksum(mp),
converged=model["parameters"]["converged"],
iterations=model["parameters"]["iterations"],
metrics=aggregate(metrics),
windows=metrics,
seconds=time.monotonic() - started,
)
)
write(
root / "development-progress.json",
dict(
completed=len(rows),
total=4 * len(protocol["candidates"]),
last=rows[-1],
elapsed_seconds=time.monotonic() - start,
),
)
choice = select_candidate(rows, protocol["baseline"])
write(
root / "development-result.json",
dict(
rows=rows,
selection=choice,
seconds=time.monotonic() - start,
protocol_sha256=checksum(root / "protocol.json"),
source_sha256=checksum(Path(__file__)),
),
)
write(
root / "development-selection.json",
dict(
**choice,
development_sha256=checksum(root / "development-result.json"),
protocol_sha256=checksum(root / "protocol.json"),
frozen_before_control_evaluation=True,
),
)
print(json.dumps(choice))
def final_fit(root):
import torch
from dataset_store import checksum, read, write
torch.set_num_threads(3)
protocol, records = setup(root)
choice = read(root / "development-selection.json")
assert choice["development_sha256"] == checksum(root / "development-result.json")
assert not (root / "models-frozen.json").exists() and not (root / "result.json").exists()
selected = {protocol["baseline"], choice["selected"]}
result = {}
for candidate in protocol["candidates"]:
if candidate["id"] not in selected:
continue
units = []
for r in records:
if r["split"] != "train":
continue
with np.load(root / r["cache"]) as z:
units.append(
samples(
features(z, candidate["representation"]), z["target"], r, protocol["fit"]
)
)
result[candidate["id"]] = fit_candidate(units, candidate)
assert result[candidate["id"]]["parameters"]["converged"]
parent = read(Path("/store/experiments/semantic-nonlinear-20261023/models-frozen.json"))
# Exact numeric baseline identity is checked against the previous fixed experiment.
previous = parent["models"]["linear"]
current = result[protocol["baseline"]]["parameters"]
for key in ["mean", "scale", "coefficients"]:
assert np.array_equal(current[key], previous[key]), key
write(
root / "models-frozen.json",
dict(
models=result,
selection_sha256=checksum(root / "development-selection.json"),
protocol_sha256=checksum(root / "protocol.json"),
baseline_exactly_reproduced=True,
production_eligible=False,
frozen_before_controls=True,
),
)
print(json.dumps({"fitted": sorted(result), "baseline_exactly_reproduced": True}))
def control_evaluation(root):
import torch
from admission_store import pixel_target
from dataset_store import checksum, read, write
torch.set_num_threads(3)
protocol, records = setup(root)
choice = read(root / "development-selection.json")
frozen = read(root / "models-frozen.json")
assert frozen["selection_sha256"] == checksum(root / "development-selection.json")
assert not (root / "result.json").exists()
rows = []
audit = {}
for r in records:
if r["split"] != "regression":
continue
with np.load(root / r["cache"]) as z:
target = z["target"]
predictions = {}
for key, model in frozen["models"].items():
pred = predict(
features(z, model["candidate"]["representation"]),
target.shape,
np.arange(target.size),
model,
).reshape(target.shape)
predictions[key] = pred
rows.append(
dict(name=r["name"], group=r["group"], candidate=key, **counts(pred, target))
)
if r["name"] == "P1":
runs = read(root / "p1-audit-runs-final.json")
from admission_store import pixel_target
t = np.frombuffer(
pixel_target(dict(runs, size=[target.shape[1], target.shape[0]])),
dtype="uint8",
).reshape(target.shape)
audit[key] = aggregate([counts(pred, t)])
np.savez_compressed(root / "cache" / (r["name"] + "-predictions.npz"), **predictions)
metrics = {
g: {
c: aggregate([r for r in rows if r["group"] == g and r["candidate"] == c])
for c in frozen["models"]
}
for g in sorted({r["group"] for r in rows})
}
b, s = protocol["baseline"], choice["selected"]
failures = []
for g, mm in metrics.items():
for key, sign in [("recall", 1), ("fpr", -1)]:
if mm[b][key] is not None and sign * (mm[s][key] - mm[b][key]) < -1e-12:
failures.append(g + ": " + key)
if audit[s]["recall"] < audit[b]["recall"] or audit[s]["fpr"] >= audit[b]["fpr"]:
failures.append("P1 diagnostic recall/gap gate")
if s == b:
failures.append("No development improvement selected")
write(
root / "result.json",
dict(
rows=rows,
metrics=metrics,
p1_diagnostic=audit,
selection=choice,
qualification=dict(accepted=not failures, failures=failures, production_eligible=False),
protocol_sha256=checksum(root / "protocol.json"),
source_sha256=checksum(Path(__file__)),
models_sha256=checksum(root / "models-frozen.json"),
control_selection=False,
),
)
print(json.dumps({"metrics": metrics, "audit": audit, "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"))
args = ap.parse_args()
{"development": development, "fit": final_fit, "evaluate": control_evaluation}[args.phase](
args.root
)
@@ -0,0 +1,107 @@
"""Offline loss policy for two immutable annotation releases.
History cohorts are not paint-quality labels. Keep class/street/window mass fixed;
only split that mass equally between original and newly reviewed pixels.
"""
import math
import numpy as np
from spatial_decoder_probe import dense_weights
from transfer_gates import component_regressions
def release_balanced_weights(records):
if not records or any(r["split"] != "train" for r in records):
raise ValueError("Training records only")
if len({r["name"] for r in records}) != len(records):
raise ValueError("Duplicate sample")
for r in records:
t, old = r["target"], r["old_target"]
if (
t.shape != old.shape
or not set(np.unique(t)) <= {0, 1, 255}
or not set(np.unique(old)) <= {0, 1, 255}
):
raise ValueError("Invalid target contract")
if not np.array_equal(t[old != 255], old[old != 255]):
raise ValueError("Original labels changed")
weights = dense_weights(records)
for r in records:
t, old, w = r["target"], r["old_target"], weights[r["name"]]
for label in (0, 1):
mask = t == label
cohorts = [mask & (old != 255), mask & (old == 255)]
present = [part for part in cohorts if part.any()]
if len(present) == 2:
mass = w[mask].sum(dtype=np.float64)
for part in present:
w[part] = mass / 2 / part.sum()
return weights
def assess_balance(rows, seeds):
expected = {"old-linear", "new-linear"} | {
f"{policy}-{family}-{seed}"
for policy in ["uniform", "balanced"]
for family in ["head", "decoder"]
for seed in seeds
}
if not seeds or len(set(seeds)) != len(seeds):
raise ValueError("Unique preregistered seeds required")
if not rows or any(r["phase"] != "development" for r in rows):
raise ValueError("Development only")
if {r["arm"] for r in rows} != expected:
raise ValueError("Incomplete arms")
groups = {r["held_out"] for r in rows}
if len(groups) != 4:
raise ValueError("Four physical streets required")
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("Unpaired or duplicate folds")
if any(not r["completed"] or r["held_out"] in r["fitted_groups"] for r in rr):
raise ValueError("Incomplete or leaked fit")
errors = []
for r in rr:
m = r["metrics"]
if any(
m[k] is None or not math.isfinite(m[k]) or not 0 <= m[k] <= 1
for k in ["recall", "fpr"]
):
raise ValueError("Invalid development support")
errors.append((1 - m["recall"] + m["fpr"]) / 2)
summary[arm] = dict(mean=sum(errors) / 4, worst=max(errors))
audits = []
eligible = []
policy_non_regressing = []
for family in ["head", "decoder"]:
passed = True
paired_passed = True
for seed in seeds:
arm = f"balanced-{family}-{seed}"
references = {"old-linear", "new-linear", f"uniform-{family}-{seed}"}
if family == "decoder":
references.add(f"balanced-head-{seed}")
for ref in sorted(references):
cc = component_regressions(rows, ref, [arm])
a, b = summary[arm], summary[ref]
composite = a["mean"] < b["mean"] - 1e-12 and a["worst"] <= b["worst"] + 1e-12
audits.append(dict(arm=arm, composite_pass=composite, **cc))
passed &= composite and cc["all_components_non_regressing"]
if ref == f"uniform-{family}-{seed}":
paired_passed &= composite and cc["all_components_non_regressing"]
if passed:
eligible.append("balanced-" + family)
if paired_passed:
policy_non_regressing.append("balanced-" + family)
return dict(
eligible_families=eligible,
paired_policy_pass=policy_non_regressing,
summaries=summary,
audits=audits,
all_seeds_required=True,
production_eligible=False,
control_selection=False,
)
@@ -0,0 +1,234 @@
"""Offline paired review-coverage experiment over frozen visual features."""
import argparse
import json
import time
from pathlib import Path
import numpy as np
from pixel_growth_probe import aggregate, counts, fit, resize_plane
from scipy.special import expit
def check_pair(sparse, dense, before, after):
for field in ["sample_id", "source", "physical_group", "split", "inputs"]:
if sparse[field] != dense[field]:
raise ValueError("Changed paired input: " + field)
if before.shape != after.shape or not set(np.unique(after)) <= {0, 1, 255}:
raise ValueError("Invalid dense target")
known = before != 255
if not np.array_equal(before[known], after[known]):
raise ValueError("Existing reviewed labels changed")
if sparse["split"] != "train" and not np.array_equal(before, after):
raise ValueError("Original control target changed")
def qualify(metrics, audit, reproduced):
failures, gains = [], []
if not reproduced:
failures.append("sparse baseline did not reproduce prior control counts")
for group, variants in metrics.items():
for metric, sign in [("recall", 1), ("fpr", -1)]:
a, b = variants["sparse"][metric], variants["dense"][metric]
if a is None or b is None:
continue
if sign * (b - a) < -1e-12:
failures.append(group + ": " + metric)
if sign * (b - a) > 1e-12:
gains.append(group + ": " + metric)
if audit["dense"]["recall"] < audit["sparse"]["recall"]:
failures.append("diagnostic paint recall")
if audit["dense"]["fpr"] >= audit["sparse"]["fpr"]:
failures.append("diagnostic gap false positives not strictly reduced")
if not gains:
failures.append("no strict gain on original regression")
return dict(accepted=not failures, failures=failures, gains=gains)
def load_examples(store, receipt):
from admission_store import Supervision, pixel_target
examples, targets = {}, {}
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]
examples[e["sample_id"]] = e
targets[e["sample_id"]] = np.frombuffer(pixel_target(t), dtype="uint8").reshape(
t["size"][1], t["size"][0]
)
return examples, targets
def samples(features, target, record, params):
if record["split"] != "train":
raise ValueError("Only train records may provide fitting samples")
import torch
h, w = target.shape
rng = np.random.default_rng(params["seed"] + int(record["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(features)[None],
torch.from_numpy(grid)[None, None],
mode="bilinear",
padding_mode="border",
align_corners=False,
)[0, :, 0].T.numpy()
return dict(
name=record["name"], group=record["group"], split="train", x=x, y=target.ravel()[chosen]
)
def run(root, store):
import torch
from admission_store import pixel_target
from dataset_store import checksum, read, write
torch.set_num_threads(3)
start = time.monotonic()
assert not (root / "models-frozen.json").exists() and not (root / "result.json").exists()
protocol = read(root / "protocol.json")
frozen = read(root / "review-frozen.json")
manifest = read(root / "feature-manifest.json")
parent = store / "experiments" / protocol["parent"]
assert frozen["source_sha256"] == checksum(Path(__file__))
assert (
manifest["protocol_sha256"] == frozen["protocol_sha256"] == checksum(root / "protocol.json")
)
assert frozen["audit_sha256"] == checksum(root / "p1-audit-runs-final.json")
assert frozen["pixel_runs_sha256"] == checksum(root / "pixel-runs-final.json")
assert frozen["regions_sha256"] == checksum(root / "regions-final.json")
assert checksum(root / "model-inventory.json") == checksum(parent / "model-inventory.json")
params = protocol["fit"]
assert params == read(parent / "protocol.json")["fit"]
old_receipt = read(parent / "supervision-receipt.json")
assert old_receipt["sha256"] == protocol["parent_release_sha256"]
old, before = load_examples(store, old_receipt)
new, after = load_examples(store, read(root / "supervision-receipt.json"))
assert set(old) == set(new) == {r["sample_id"] for r in manifest["records"]}
units = {"sparse": [], "dense": []}
for r in manifest["records"]:
sid = r["sample_id"]
check_pair(old[sid], new[sid], before[sid], after[sid])
assert checksum(root / r["cache"]) == r["sha256"]
with np.load(root / r["cache"]) as z:
assert np.array_equal(z["target"], after[sid])
if r["split"] == "train":
for arm, target in [("sparse", before[sid]), ("dense", after[sid])]:
units[arm].append(samples(z["features"].astype("float32"), target, r, params))
models = {arm: fit(us, params["l2"], params["max_iterations"]) for arm, us in units.items()}
fit_seconds = time.monotonic() - start
write(
root / "models-frozen.json",
dict(
models=models,
threshold=params["threshold"],
protocol_sha256=checksum(root / "protocol.json"),
review_sha256=checksum(root / "review-frozen.json"),
features_sha256=checksum(root / "feature-manifest.json"),
source_sha256=checksum(Path(__file__)),
frozen_before_evaluation=True,
),
)
rows = []
diagnostic = None
old_rows = {r["name"]: r for r in read(parent / "result.json")["rows"]}
for r in manifest["records"]:
if r["split"] != "regression":
continue
with np.load(root / r["cache"]) as z:
features = z["features"].astype("float32")
target = z["target"]
predictions = {}
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", features, scaled) + bias
predictions[arm] = (
expit(resize_plane(logits[None], target.shape)[0]) >= params["threshold"]
)
np.savez_compressed(root / "cache" / (r["name"] + "-predictions.npz"), **predictions)
rows.append(
dict(
name=r["name"],
group=r["group"],
variants={arm: counts(p, target) for arm, p in predictions.items()},
)
)
if r["name"] == "P1":
t = read(root / "p1-audit-runs-final.json")
audit_target = np.frombuffer(
pixel_target(dict(t, size=[512, 512])), dtype="uint8"
).reshape(512, 512)
diagnostic = {
arm: aggregate([counts(p, audit_target)]) for arm, p in predictions.items()
}
assert diagnostic is not None
metrics = {
g: {arm: aggregate([r["variants"][arm] for r in rows if r["group"] == g]) for arm in models}
for g in sorted({r["group"] for r in rows})
}
reproduced = all(
r["variants"]["sparse"] == old_rows[r["name"]]["variants"]["expanded"] for r in rows
)
prior_model = read(parent / "models-frozen.json")["models"]["expanded"]
delta = max(
float(np.max(np.abs(np.array(models["sparse"][k]) - np.array(prior_model[k]))))
for k in ["mean", "scale", "coefficients"]
)
outcome = qualify(metrics, diagnostic, reproduced)
write(
root / "result.json",
dict(
**outcome,
metrics=metrics,
rows=rows,
diagnostic=diagnostic,
sparse_reproduced=reproduced,
sparse_max_parameter_delta=delta,
models_sha256=checksum(root / "models-frozen.json"),
source_sha256=checksum(Path(__file__)),
protocol_sha256=checksum(root / "protocol.json"),
fit_and_load_seconds=fit_seconds,
total_seconds=time.monotonic() - start,
evaluated_utc=__import__("datetime")
.datetime.now(__import__("datetime").timezone.utc)
.isoformat(),
production_eligible=False,
blind_generalization_claim=False,
),
)
print(
json.dumps(
dict(
**outcome,
metrics=metrics,
diagnostic=diagnostic,
sparse_reproduced=reproduced,
parameter_delta=delta,
)
)
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("root", type=Path)
parser.add_argument("--store", type=Path, default=Path("/store"))
args = parser.parse_args()
run(args.root, args.store)
@@ -0,0 +1,56 @@
"""Separate recall and false-positive regressions by physical validation group.
Diagnostic/future protocol helper. Does not rewrite an experiment's frozen choice.
"""
import math
def component_regressions(rows, reference, candidates):
if not rows or any(r["phase"] != "development" for r in rows):
raise ValueError("Development rows only")
selected = {reference, *candidates}
by_arm = {a: {} for a in selected}
for row in rows:
if row["arm"] not in selected:
continue
group = row["held_out"]
if group in row["fitted_groups"] or group in by_arm[row["arm"]]:
raise ValueError("Leaked or duplicate physical group")
if not row["completed"]:
raise ValueError("Incomplete fit")
by_arm[row["arm"]][group] = row["metrics"]
groups = set(by_arm[reference])
if not groups or any(set(by_arm[a]) != groups for a in candidates):
raise ValueError("Unmatched physical groups")
regressions = []
for arm in candidates:
for group in sorted(groups):
for metric, direction in [("recall", 1), ("fpr", -1)]:
before = by_arm[reference][group][metric]
after = by_arm[arm][group][metric]
if before is None and after is None:
continue
if (
before is None
or after is None
or not all(math.isfinite(x) and 0 <= x <= 1 for x in [before, after])
):
raise ValueError("Inconsistent metric support")
if direction * (after - before) < -1e-12:
regressions.append(
dict(
arm=arm,
group=group,
metric=metric,
before=before,
after=after,
delta=after - before,
)
)
return dict(
reference=reference,
candidates=list(candidates),
regressions=regressions,
all_components_non_regressing=not regressions,
)
@@ -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]))
@@ -0,0 +1,63 @@
"""Explicit TRAIN-only paint additions over immutable labels; never infer background."""
import hashlib
import numpy as np
from condition_inventory import raster
from PIL import Image, ImageFilter
def add_fragments(sample, review, old, approved_roi):
if sample["split"] != "train" or review["name"] != sample["name"]:
raise ValueError("Pinned TRAIN sample required")
if review["input_sha256"] != sample["rgb_sha256"]:
raise ValueError("Image identity changed")
if old.dtype != np.uint8 or list(old.shape[::-1]) != sample["size"]:
raise ValueError("Invalid target shape/type")
if not np.isin(old, [0, 1, 255]).all():
raise ValueError("Invalid target classes")
expected = sample["target_sha256"]
if sample["kind"] == "existing":
if expected is None or hashlib.sha256(old.tobytes()).hexdigest() != expected:
raise ValueError("Existing target changed")
elif sample["kind"] != "candidate" or expected is not None or np.any(old != 255):
raise ValueError("Candidate already has unbound labels")
if review["target_sha256"] != expected or review["boundary_ignore_px"] != 1:
raise ValueError("Pinned target/uncertainty policy required")
polygons = review["paint_fragments"]
if not isinstance(polygons, list) or not 1 <= len(polygons) <= 64:
raise ValueError("Bounded explicit fragments required")
mask = np.zeros(old.shape, dtype=bool)
roi = raster(approved_roi, sample["size"])
for polygon in polygons:
part = raster(polygon, sample["size"])
if np.any(part & ~roi):
raise ValueError("Fragment escaped prereviewed region")
mask |= part
core = (
np.array(Image.fromarray(mask.astype("uint8") * 255).filter(ImageFilter.MinFilter(3))) > 0
)
if np.any(core & (old == 0)):
raise ValueError("Paint conflicts with accepted background")
added = core & (old == 255)
if not added.any():
raise ValueError("No new visible paint survived uncertainty erosion")
result = old.copy()
result[added] = 1
return result, added
def runs(target):
result = dict(view="top", paint=[], background=[], unknown=[])
for name, label in [("paint", 1), ("background", 0)]:
for y, row in enumerate(target == label):
edges = np.diff(np.pad(row.astype("int8"), (1, 1)))
result[name].extend(
[
[y, int(a), int(b)]
for a, b in zip(
np.flatnonzero(edges == 1), np.flatnonzero(edges == -1), strict=True
)
]
)
return result
@@ -0,0 +1,72 @@
"""Paired whole-street guards for a fixed weak-paint coverage intervention."""
import math
def assess(rows, seeds):
arms = {f"{policy}-{seed}" for policy in ["base", "added"] for seed in seeds}
if not seeds or len(set(seeds)) != len(seeds) or {r["arm"] for r in rows} != arms:
raise ValueError("Complete preregistered seed pairs required")
groups = {r["held_out"] for r in rows}
if len(groups) != 4 or len(rows) != 2 * len(seeds) * 4:
raise ValueError("Four complete physical-street pairs required")
keyed = {}
for r in rows:
key = r["held_out"], r["arm"]
if key in keyed or r["phase"] != "development" or not r["completed"]:
raise ValueError("Duplicate/incomplete/non-development row")
if set(r["fitted_groups"]) != groups - {r["held_out"]}:
raise ValueError("Incomplete or leaked physical groups")
for part, metric in [
("weak", "recall"),
("clear", "recall"),
("original", "recall"),
("original", "fpr"),
]:
value = r[part][metric]
if value is None or not math.isfinite(value) or not 0 <= value <= 1:
raise ValueError("Required evaluation support missing")
keyed[key] = r
summary = []
for seed in seeds:
failures = []
deltas = []
for group in sorted(groups):
a, b = keyed[group, f"added-{seed}"], keyed[group, f"base-{seed}"]
for part in ["weak", "clear", "original", "added"]:
for k in ["tp", "fn", "fp", "tn"]:
if k in ["tp", "fp"]:
opposite = "fn" if k == "tp" else "tn"
if a[part][k] + a[part][opposite] != b[part][k] + b[part][opposite]:
raise ValueError("Unpaired evaluation targets")
for part, metric, sign in [
("weak", "recall", 1),
("clear", "recall", 1),
("original", "recall", 1),
("original", "fpr", -1),
]:
if sign * (a[part][metric] - b[part][metric]) < -1e-12:
failures.append(
dict(
group=group,
part=part,
metric=metric,
before=b[part][metric],
after=a[part][metric],
)
)
deltas.append(a["weak"]["recall"] - b["weak"]["recall"])
mean_delta = sum(deltas) / 4
if mean_delta <= 1e-12:
failures.append(dict(metric="mean weak recall", delta=mean_delta))
summary.append(
dict(
seed=seed, mean_weak_recall_gain=mean_delta, passed=not failures, failures=failures
)
)
return dict(
passed=all(r["passed"] for r in summary),
seeds=summary,
production_eligible=False,
all_seeds_required=True,
)
@@ -0,0 +1,36 @@
"""Native Torch weighted CE on reviewed paint/background; unknown contributes zero."""
import math
def weighted_paint_cross_entropy(logits, target, class_weights):
"""Mean divides by summed valid class weights, including BG-only batches.
Weights are supplied by a frozen TRAIN-only recipe; this function never
estimates them from evaluation labels or adjusts a prediction threshold.
Torch is optional until training calls this function.
"""
import torch
from torch.nn import functional as functional
if len(class_weights) != 2 or any(
not math.isfinite(float(w)) or float(w) <= 0 for w in class_weights
):
raise ValueError("Two finite positive class weights required")
if logits.ndim != 4 or logits.shape[1] != 2:
raise ValueError("Native NCHW logits with two classes required")
if target.shape != (logits.shape[0], *logits.shape[2:]):
raise ValueError("Native NHW target must match logits")
if target.dtype != torch.long:
raise ValueError("Integer class indices required")
valid = target != 255
if not bool(valid.any()):
raise ValueError("All-unknown loss forbidden")
if not bool(((target == 0) | (target == 1) | ~valid).all()):
raise ValueError("Target classes must be 0, 1 or 255")
weights = logits.new_tensor(class_weights)
if not bool(torch.isfinite(weights).all() & (weights > 0).all()):
raise ValueError("Class weights not representable in logits dtype")
return functional.cross_entropy(
logits, target, weight=weights, ignore_index=255, reduction="mean"
)
+434
View File
@@ -0,0 +1,434 @@
"""Separate Worker inbox/builder. No local-Mac fallback; no inference changes."""
import argparse
import json
import logging
import os
import shutil
import subprocess
import time
from logging.handlers import RotatingFileHandler
from pathlib import Path
from core_client import CoreClient
from dataset_store import Store, checksum, read, verify, write
from final_snapshot import plan
from infrastructure_gaussian_sources import resolve_gaussian_entry
HERE = Path(__file__).resolve().parent
IMAGE = "sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0"
def docker(*args, **kw):
return subprocess.run(["docker", *map(str, args)], capture_output=True, check=True, **kw)
def source_for(envelope, store, state):
bundle = envelope["source"]["bundle_sha256"]
for root in (store.root / "sources", state / "infrastructure-sources"):
for receipt in sorted(root.glob("*/source.json")):
source = read(receipt)
if source.get("bundle_sha256") == bundle:
if checksum(receipt.parent / source["ply"]) != source["sha256"]:
raise ValueError("Cached Gaussian source changed")
return receipt.parent, source
# Complete conversion is shared across subsequent crops and kept only on
# Worker, inside the learning quota. Producer inputs remain read-only.
store.capacity(6 * 1024**3)
profile = dict(
producer_data="D:/NDC_GAUSSIAN_PIPELINE/data",
sevenzip="C:/Program Files/7-Zip/7z.exe",
splat_transform="tools/splat-transform-3.4.0/node_modules/@playcanvas/splat-transform/bin/cli.mjs",
)
entry, native = resolve_gaussian_entry(
envelope["source"], envelope["world"], Path(profile["producer_data"])
)
converter = state.parent / profile["splat_transform"]
from dataset_store import digest
key = digest(
dict(
bundle=bundle,
converter=checksum(converter),
adapter="learning-lcc-lod1-native-frame-v1",
)
)
root = store.root / "sources" / key
root.mkdir(exist_ok=True)
ply = root / "full-lod1.ply"
partial = root / "building.ply"
command = [
shutil.which("node"),
"--max-old-space-size=8192",
str(converter),
"--gpu",
"cpu",
"--max-workers",
"4",
"-w",
"--select-lod",
"1",
str(entry),
"-r",
"180,0,0",
str(partial),
]
from native_children import NativeChildren
children = NativeChildren()
with (root / "conversion.log").open("wb") as log:
proc = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT)
try:
children.assign(proc)
deadline = time.monotonic() + 900
while proc.poll() is None:
store.capacity(0)
if time.monotonic() > deadline:
raise TimeoutError("Gaussian conversion budget exceeded")
time.sleep(2)
if proc.returncode:
raise RuntimeError("Gaussian conversion failed; see bounded source log")
finally:
if proc.poll() is None:
subprocess.run(
["taskkill", "/PID", str(proc.pid), "/T", "/F"], capture_output=True, timeout=30
)
proc.wait(timeout=30)
children.close()
store.capacity(0)
with partial.open("rb") as stream:
header = stream.read(65536).split(b"end_header", 1)[0]
if not all(name in header for name in (b"opacity", b"scale_0", b"rot_0", b"f_dc_0")):
raise ValueError("Conversion lacks Gaussian attributes")
os.replace(partial, ply)
source = dict(
ply=ply.name,
sha256=checksum(ply),
bundle_sha256=bundle,
lod=1,
converter_sha256=checksum(converter),
native_entrypoint=native["entrypoint"],
source_to_world=[[1, 0, 0, 0], [0, 0, -1, 0], [0, 1, 0, 0], [0, 0, 0, 1]],
gaussian_only=True,
collider_input=False,
point_cloud_input=False,
trajectory_used=False,
camera_source="explicit-local-review-window",
)
write(root / "source.json", source)
return root, source
def sync(client, store):
for item in client.request("/worker/semantic-edits/pending")["jobs"]:
try:
key, world = item["revision"], item["world_id"]
annotation = client.request(
f"/worker/worlds/{world}/semantic-edits/{key}", max_response_bytes=24 * 1024**2
)
envelope = dict(
annotation=annotation,
world=client.request("/worlds/" + world),
source=client.request(
"/worker/worlds/" + world + "/infrastructure-source",
max_response_bytes=24 * 1024**2,
),
renderer_image=IMAGE,
)
store.accept(envelope)
except Exception:
logging.exception("Delivery deferred for revision %s", item["revision"])
acknowledge(client, store)
def acknowledge(client, store):
# ACK after a durable inbox commit; replay also covers a lost HTTP response.
for key, receipt in store.db.execute(
"SELECT id,receipt FROM jobs WHERE acknowledged IS NULL "
"OR acknowledged != receipt ORDER BY rowid"
).fetchall():
envelope = read(store.root / "inbox" / (key + ".json"))
world = envelope["world"]["world_id"]
client.request(f"/worker/worlds/{world}/semantic-edits/{key}/receipt", json.loads(receipt))
with store.db:
store.db.execute("UPDATE jobs SET acknowledged=? WHERE id=?", (receipt, key))
def occupied(state):
return any(
(state / name).exists()
for name in (
"active.json",
"editor-active.json",
"route-active.json",
"infrastructure-active.json",
)
)
def build(key, store, state):
container = "ndc-semantic-sample-" + key[:16]
# Only our exact owned name, left after a killed host process, is reconciled.
prior = subprocess.run(
["docker", "inspect", container, "--format", '{{index .Config.Labels "com.nodedc.role"}}'],
capture_output=True,
timeout=15,
)
if prior.returncode == 0:
if prior.stdout.decode().strip() != "semantic-sample":
raise ValueError("Container name belongs to another owner")
docker("rm", "-f", container, timeout=30)
staging = store.root / "work" / key
staging.mkdir(exist_ok=True)
output = staging / "dataset"
output.mkdir(exist_ok=True)
envelope = read(store.root / "inbox" / (key + ".json"))
if store.accept(envelope) != key:
raise ValueError("Stored inbox revision changed")
snapshot = plan(envelope["annotation"]["package"])
plan_path = staging / "plan.json"
if plan_path.exists() and read(plan_path) != snapshot:
raise ValueError("Resumed snapshot identity changed")
write(plan_path, snapshot)
execution = dict(
release=read(HERE / "release.json")["id"],
renderer=IMAGE,
annotation=envelope["annotation"]["sha256"],
)
execution_path = staging / "execution.json"
if execution_path.exists() and read(execution_path) != execution:
raise ValueError("Resume requires the original builder/image/annotation identity")
write(execution_path, execution)
source_dir, source = source_for(envelope, store, state)
source = dict(
source,
world_sha256=envelope["world"]["sha256"],
collider_sha256=envelope["world"].get("collider_sha256"),
)
store.capacity(512 * 1024**2)
write(staging / "envelope.json", envelope)
write(staging / "source.json", source)
kernels = store.root / "cache" / IMAGE.removeprefix("sha256:")
kernels.mkdir(parents=True, exist_ok=True)
image_env = json.loads(
docker("image", "inspect", IMAGE, "--format", "{{json .Config.Env}}", timeout=20).stdout
)
inherited = next((e.partition("=")[2] for e in image_env if e.startswith("PYTHONPATH=")), "")
cmd = [
"run",
"--detach",
"--name",
container,
"--gpus",
"all",
"--memory",
"6g",
"--cpus",
"4",
"--network",
"none",
"--read-only",
"--cap-drop",
"ALL",
"--security-opt",
"no-new-privileges",
"--tmpfs",
"/tmp:rw,exec,size=1073741824",
"--label",
"com.nodedc.product=mission-core",
"--label",
"com.nodedc.stack=semantic-learning",
"--label",
"com.nodedc.role=semantic-sample",
"--label",
"com.nodedc.managed-by=semantic-learning-worker",
"--log-driver",
"local",
"--log-opt",
"max-size=2m",
"--log-opt",
"max-file=2",
"-e",
"PYTHONPATH=/builder:" + inherited,
"-e",
"PYTHONDONTWRITEBYTECODE=1",
"-e",
"XDG_CACHE_HOME=/tmp/cache",
"-e",
"TORCH_EXTENSIONS_DIR=/kernels",
"-v",
str(HERE) + ":/builder:ro",
"-v",
str(kernels) + ":/kernels",
"-v",
str(source_dir) + ":/input:ro",
"-v",
str(staging) + ":/job:ro",
"-v",
str(output) + ":/output",
"--entrypoint",
"python3",
IMAGE,
"-B",
"/builder/build_samples.py",
]
started = time.monotonic()
shards = {}
for start in range(0, len(snapshot["windows"]), 4):
name = f"part-{start // 4:03d}"
part = output / name
if (part / "dataset.json").exists():
shards[name] = verify(part)
continue
if part.exists():
shutil.rmtree(part) # Only the unfinished owned shard; complete shards are immutable.
if occupied(state):
raise InterruptedError("Yielding GPU before next shard")
store.capacity(512 * 1024**2)
write(
staging / "batch.json",
dict(name=name, start=start, stop=start + 4, classes=snapshot["classes"]),
)
run_shard(cmd, container, store, state)
shards[name] = verify(part)
write(
staging / "progress.json",
dict(
completed=len(shards),
total=(len(snapshot["windows"]) + 3) // 4,
seconds=time.monotonic() - started,
),
)
write(output / "plan.json", snapshot)
(output / "dataset_reader.py").write_bytes((HERE / "dataset_store.py").read_bytes())
files = {
p.name: dict(sha256=checksum(p), bytes=p.stat().st_size)
for p in (output / "plan.json", output / "dataset_reader.py")
}
write(
output / "dataset.json",
dict(
schema_version="missioncore.semantic-collection/v1",
shards=shards,
files=files,
training_eligible=False,
revision=key,
world_sha256=snapshot["world_sha256"],
split_group=snapshot["world_sha256"],
classes=snapshot["classes"],
seconds=time.monotonic() - started,
),
)
result = store.publish(key, output)
shutil.rmtree(staging)
return result
def run_shard(cmd, container, store, state):
try:
docker(*cmd, timeout=30)
deadline = time.monotonic() + 600
while True:
status = json.loads(
docker("inspect", container, "--format", "{{json .State}}", timeout=15).stdout
)
if not status["Running"]:
if status["ExitCode"]:
logs = docker("logs", "--tail", "30", container, timeout=15)
log = (logs.stdout + logs.stderr).decode(errors="replace")
raise RuntimeError("Renderer failed: " + log[-4000:])
break
store.capacity(0)
if occupied(state):
raise InterruptedError("Yielding GPU to simulation/infrastructure")
if time.monotonic() > deadline:
raise TimeoutError("Sample rendering budget exceeded")
time.sleep(1)
finally:
subprocess.run(["docker", "rm", "-f", container], capture_output=True, timeout=30)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--root", type=Path, required=True)
parser.add_argument("--state", type=Path, required=True)
parser.add_argument("--token-file", type=Path, required=True)
parser.add_argument("--core", default="http://127.0.0.1:18080")
parser.add_argument("--once", action="store_true")
args = parser.parse_args()
if os.name != "nt" or not args.root.is_absolute() or args.root.resolve().is_relative_to(HERE):
raise ValueError("Durable learning requires a separate Worker Windows store")
store = Store(args.root)
import msvcrt
lock = (args.root / "worker.lock").open("a+b")
lock.seek(0)
lock.write(b"0")
lock.flush()
lock.seek(0)
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1)
handler = RotatingFileHandler(
args.root / "logs/worker.log", maxBytes=2 * 1024**2, backupCount=2, encoding="utf-8"
)
logging.basicConfig(
level=logging.INFO, handlers=[handler], format="%(asctime)s %(levelname)s %(message)s"
)
# A process death does not kill Docker. Reconcile only this store's names
# before resuming an unfinished build or acknowledging a published sample.
for (key,) in store.db.execute(
"SELECT id FROM jobs WHERE acknowledged IS NULL "
"OR acknowledged != receipt OR state='building'"
).fetchall():
name = "ndc-semantic-sample-" + key[:16]
found = subprocess.run(
["docker", "inspect", name, "--format", '{{index .Config.Labels "com.nodedc.role"}}'],
capture_output=True,
timeout=15,
)
if found.returncode == 0 and found.stdout.decode().strip() == "semantic-sample":
docker("rm", "-f", name, timeout=30)
client = CoreClient(args.core, args.token_file, "semantic-learning-v1")
while True:
try:
sync(client, store)
except Exception:
logging.exception("Core delivery/receipt unavailable; durable Worker inbox retained")
try:
if not occupied(args.state):
key = store.next()
if key:
logging.info("Preparing revision %s", key)
started = time.monotonic()
try:
try:
acknowledge(client, store)
except Exception:
logging.warning(
"Progress receipt deferred; preparation stays on Worker"
)
result = build(key, store, args.state)
logging.info(
"Published %s samples=%s seconds=%.3f",
key,
result["sample_count"],
time.monotonic() - started,
)
except InterruptedError:
# Scheduling yield is not an invalid annotation attempt.
with store.db:
store.db.execute(
"UPDATE jobs SET attempts=attempts-1 WHERE id=?", (key,)
)
logging.info("GPU yielded for %s", key)
except Exception as exc:
logging.exception("Sample failed %s", key)
store.update(key, "failed", error=str(exc)[:4096])
except Exception:
logging.exception("Worker build cycle unavailable")
if args.once:
break
time.sleep(10)
if __name__ == "__main__":
main()