Files
NODEDC_MISSION_CORE/simulation/semantic-learning/feature_refinement.py
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

98 lines
4.2 KiB
Python

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