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