Files
NODEDC_MISSION_CORE/tests/test_native_detail.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

261 lines
10 KiB
Python

import importlib.util
import sys
from pathlib import Path
import pytest
def load_module():
source = Path(__file__).parents[1] / "simulation/semantic-learning/native_detail.py"
if not source.exists():
source = Path(__file__).with_name("native_detail.py")
spec = importlib.util.spec_from_file_location("native_detail", source)
module = importlib.util.module_from_spec(spec)
# The standalone Worker package keeps native_detail and feature_refinement
# together; the repository tests import from their source directory instead.
sys.path.insert(0, str(source.parent))
try:
spec.loader.exec_module(module)
finally:
sys.path.pop(0)
return module
m = load_module()
def fixture():
t = pytest.importorskip("torch")
fine = t.arange(4 * 2 * 3).float().reshape(1, 4, 2, 3) / 20 - 0.5
coarse = t.linspace(-2, 2, 7 * 11).reshape(7, 11)
rgb = ((t.arange(3 * 7 * 11) * 17) % 101).float().reshape(1, 3, 7, 11) / 100
return t, fine, coarse, rgb
def test_network_shape_identity_seed_and_rng():
t, fine, coarse, rgb = fixture()
rng = t.random.get_rng_state().clone()
default = m.network(5)
assert sum(p.numel() for p in default.parameters()) == 25602
assert [layer.in_features for layer in default.layers] == [332, 65]
assert default.output.in_features == 65
a, b = m.network(12, channels=4), m.network(12, channels=4)
assert t.equal(rng, t.random.get_rng_state())
assert all(t.equal(p, q) for p, q in zip(a.parameters(), b.parameters(), strict=True))
for arm in sorted(m.ARMS):
got = m.predict(a, fine, coarse, rgb, arm, chunk=9)
assert t.equal(got, coarse)
def test_prepare_native_and_lowpass_have_same_shape_and_fixed_center():
t = pytest.importorskip("torch")
yy, xx = t.meshgrid(t.arange(8), t.arange(10), indexing="ij")
checker = ((yy + xx) % 2).float()[None, None].expand(1, 3, -1, -1).clone()
native = m.prepare_rgb(checker, (2, 5), "native_rgb")
lowpass = m.prepare_rgb(checker, (2, 5), "lowpass_rgb")
assert native.shape == lowpass.shape == checker.shape
assert t.equal(native, checker * 2 - 1)
assert t.equal(lowpass, t.zeros_like(lowpass))
assert not t.equal(native, lowpass)
for arm in m.ARMS:
constant = t.full((1, 3, 6, 8), 0.25)
t.testing.assert_close(m.prepare_rgb(constant, (2, 4), arm), constant - 0.75)
same_grid = m.prepare_rgb(checker, (8, 10), arm)
assert t.equal(same_grid, native)
def test_lowpass_matches_explicit_area_then_bilinear_on_noninteger_grid():
t, fine, _, rgb = fixture()
low = t.nn.functional.interpolate(rgb, size=fine.shape[-2:], mode="area")
expected = t.nn.functional.interpolate(
low, size=rgb.shape[-2:], mode="bilinear", align_corners=False
)
t.testing.assert_close(m.prepare_rgb(rgb, fine.shape[-2:], "lowpass_rgb"), expected * 2 - 1)
@pytest.mark.parametrize("shape", [(6, 8), (1, 1), (1, 4), (4, 1)])
def test_patch_rgb_order_centres_and_replicated_borders(shape):
t = pytest.importorskip("torch")
h, w = shape
image = t.arange(3 * h * w).double().reshape(1, 3, h, w) / (3 * h * w)
prepared = m.prepare_rgb(image, (1, 1), "native_rgb")
indices = t.tensor([0, (h // 2) * w + w // 2, h * w - 1], dtype=t.long)
actual = m.sample_patch(prepared, indices)
# Independent scalar lookup specifies the patch contract, including corners.
expected = []
for index in indices.tolist():
cy, cx = divmod(index, w)
expected.append([
prepared[0, channel, min(max(cy + dy, 0), h - 1), min(max(cx + dx, 0), w - 1)]
for channel in range(3) for dy in range(-2, 3) for dx in range(-2, 3)
])
assert t.equal(actual, t.tensor(expected, dtype=t.float64))
for channel in range(3):
t.testing.assert_close(
actual[:, channel * 25 + 12], prepared[0, channel].flatten()[indices]
)
def test_rotate_patch_keeps_channels_and_rotates_spatial_axes_only():
t = pytest.importorskip("torch")
patch = t.arange(75).float().reshape(1, 75) / 75
for k in range(4):
rotated = m.rotate_patch(patch, k).reshape(1, 3, 5, 5)
original = patch.reshape(1, 3, 5, 5)
for channel in range(3):
assert t.equal(rotated[:, channel], t.rot90(original[:, channel], k, (-2, -1)))
assert t.equal(rotated[:, :, 2, 2], original[:, :, 2, 2])
repeated = patch
for _ in range(4):
repeated = m.rotate_patch(repeated, 1)
assert t.equal(repeated, patch)
for bad in [-1, 4, 1.0, True]:
with pytest.raises(ValueError):
m.rotate_patch(patch, bad)
def test_sample_points_fine_alignment_coarse_centres_and_empty_indices():
t, fine, coarse, rgb = fixture()
prepared = m.prepare_rgb(rgb, fine.shape[-2:], "native_rgb")
indices = t.tensor([0, 4, 20, coarse.numel() - 1], dtype=t.long)
ff, cc, pp = m.sample_points(fine, coarse, prepared, indices)
expected_fine = t.nn.functional.interpolate(
fine, size=coarse.shape, mode="bilinear", align_corners=False
)[0].flatten(1).T[indices]
t.testing.assert_close(ff, expected_fine, atol=2e-6, rtol=1e-6)
assert t.equal(cc[:, 0], coarse.flatten()[indices])
assert t.equal(pp, m.sample_patch(prepared, indices))
empty = m.sample_points(fine, coarse, prepared, t.empty(0, dtype=t.long))
assert [value.shape for value in empty] == [(0, 4), (0, 1), (0, 75)]
assert m.sample_patch(prepared, t.empty(0, dtype=t.long)).shape == (0, 75)
@pytest.mark.parametrize("arm", ["native_rgb", "lowpass_rgb"])
def test_prediction_c4_equivariance_chunking_and_explicit_logit_average(arm):
t, fine, coarse, rgb = fixture()
net = m.network(8, channels=4, width=8)
with t.no_grad():
net.output.weight.copy_(t.linspace(-0.2, 0.2, 9).reshape(1, 9))
net.output.bias.fill_(0.1)
expected = m.predict(net, fine, coarse, rgb, arm, chunk=coarse.numel())
assert not t.equal(expected, coarse)
for chunk in [1, 13, 200]:
actual = m.predict(net, fine, coarse, rgb, arm, chunk=chunk)
t.testing.assert_close(actual, expected, atol=2e-6, rtol=1e-6)
for k in range(4):
actual = m.predict(
net, t.rot90(fine, k, (-2, -1)), t.rot90(coarse, k),
t.rot90(rgb, k, (-2, -1)), arm, chunk=13,
)
t.testing.assert_close(t.rot90(actual, -k), expected, atol=3e-6, rtol=1e-6)
prepared = m.prepare_rgb(rgb, fine.shape[-2:], arm)
points, logits, patches = m.sample_points(fine, coarse, prepared, t.arange(coarse.numel()))
with t.no_grad():
four = [net(points, logits, m.rotate_patch(patches, k)) for k in range(4)]
explicit_mean = t.stack(four).mean(0).reshape(coarse.shape)
t.testing.assert_close(expected, explicit_mean, atol=2e-6, rtol=1e-6)
def test_head_parameters_get_gradients_but_inputs_stay_frozen():
t, fine, coarse, rgb = fixture()
prepared = m.prepare_rgb(rgb, fine.shape[-2:], "native_rgb")
points = m.sample_points(fine, coarse, prepared, t.tensor([0, 11, 44]))
net = m.network(3, channels=4, width=8)
loss = net(*points).square().mean()
loss.backward()
assert net.output.weight.grad is not None
assert float(net.output.weight.grad.abs().sum()) > 0
assert all(
not value.requires_grad and value.grad is None for value in (*points, fine, coarse, rgb)
)
for index in range(3):
bad = list(points)
bad[index] = bad[index].clone().requires_grad_(True)
with pytest.raises(ValueError, match="frozen"):
net(*bad)
@pytest.mark.parametrize("bad", ["fine_channels", "coarse_shape", "patch_shape", "patch_nan"])
def test_head_rejects_invalid_point_shapes_and_nonfinite_patches(bad):
t, fine, coarse, rgb = fixture()
prepared = m.prepare_rgb(rgb, fine.shape[-2:], "native_rgb")
ff, cc, pp = m.sample_points(fine, coarse, prepared, t.tensor([0, 1]))
if bad == "fine_channels":
ff = ff[:, :-1]
elif bad == "coarse_shape":
cc = cc[:, 0]
elif bad == "patch_shape":
pp = pp[:, :-1]
else:
pp[0, 0] = float("nan")
with pytest.raises(ValueError):
m.network(1, channels=4, width=8)(ff, cc, pp)
@pytest.mark.parametrize("bad", [
"rgb_shape", "rgb_negative", "rgb_above_one", "rgb_nan", "rgb_dtype", "rgb_gradient",
"fine_shape", "fine_nan", "fine_gradient", "coarse_shape", "coarse_inf",
"coarse_gradient", "dtype_mismatch", "arm", "chunk",
])
def test_predict_rejects_invalid_maps(bad):
t, fine, coarse, rgb = fixture()
net = m.network(1, channels=4, width=8)
arm, chunk = "native_rgb", 9
if bad == "rgb_shape":
rgb = rgb[:, :2]
elif bad == "rgb_negative":
rgb[0, 0, 0, 0] = -0.1
elif bad == "rgb_above_one":
rgb[0, 0, 0, 0] = 1.1
elif bad == "rgb_nan":
rgb[0, 0, 0, 0] = float("nan")
elif bad == "rgb_dtype":
rgb = (rgb * 255).to(t.uint8)
elif bad == "rgb_gradient":
rgb.requires_grad_(True)
elif bad == "fine_shape":
fine = fine[0]
elif bad == "fine_nan":
fine[0, 0, 0, 0] = float("nan")
elif bad == "fine_gradient":
fine.requires_grad_(True)
elif bad == "coarse_shape":
coarse = coarse[:, :-1]
elif bad == "coarse_inf":
coarse[0, 0] = float("inf")
elif bad == "coarse_gradient":
coarse.requires_grad_(True)
elif bad == "dtype_mismatch":
coarse = coarse.double()
elif bad == "arm":
arm = "scene_specific"
else:
chunk = 0
with pytest.raises(ValueError):
m.predict(net, fine, coarse, rgb, arm, chunk)
@pytest.mark.parametrize("bad", ["negative", "outside", "dtype", "shape"])
def test_patch_rejects_invalid_native_indices(bad):
t, fine, coarse, rgb = fixture()
prepared = m.prepare_rgb(rgb, fine.shape[-2:], "native_rgb")
indices = t.tensor([0], dtype=t.long)
if bad == "negative":
indices[0] = -1
elif bad == "outside":
indices[0] = coarse.numel()
elif bad == "dtype":
indices = indices.float()
else:
indices = indices[None]
with pytest.raises(ValueError):
m.sample_patch(prepared, indices)
@pytest.mark.parametrize("shape", [(0, 1), (2,), (2.0, 3), (True, 2), (8, 2)])
def test_prepare_rejects_invalid_or_upsampling_feature_grid(shape):
_, _, _, rgb = fixture()
with pytest.raises(ValueError):
m.prepare_rgb(rgb, shape, "lowpass_rgb")