Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
220 lines
9.1 KiB
Python
220 lines
9.1 KiB
Python
"""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)
|