Files
NODEDC_MISSION_CORE/simulation/semantic-learning/rgb_training_input.py
T
DCCONSTRUCTIONS 25dc0a1b44 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.
2026-10-29 09:10:00 +03:00

137 lines
6.0 KiB
Python

"""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),
)