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