import importlib.util from pathlib import Path import pytest def load_module(name): source = Path(__file__).parents[1] / "simulation/semantic-learning" / f"{name}.py" if not source.exists(): source = Path(__file__).with_name(f"{name}.py") spec = importlib.util.spec_from_file_location(name, source) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module m = load_module("linear_refinement") def tensors(): t = pytest.importorskip("torch") x = t.tensor([[-2., 1.], [-1., -1.], [0., 2.], [1., -2.], [2., 1.]], dtype=t.float64) c = t.tensor([[0.4], [-0.2], [0.], [-0.4], [0.2]], dtype=t.float64) y = t.tensor([0, 0, 0, 1, 1]) w = t.tensor([1., 2., 0., 3., 1.], dtype=t.float64) return t, x, c, y, w def test_identity_parameter_count_and_rng_preservation(): t = pytest.importorskip("torch") rng = t.random.get_rng_state().clone() a, b = m.network(1), m.network(999) assert t.equal(rng, t.random.get_rng_state()) assert sum(p.numel() for p in a.parameters()) == 258 assert all(t.equal(p, q) for p, q in zip(a.parameters(), b.parameters(), strict=True)) fine, coarse = t.ones(7, 256), t.arange(7).float().reshape(-1, 1) for arm in m.ARMS: assert t.equal(a(fine, coarse, arm), coarse) def test_predict_native_alignment_chunking_and_ablation(): t = pytest.importorskip("torch") feature = load_module("feature_refinement") net = m.network(channels=2) with t.no_grad(): net.weight.copy_(t.tensor([[0.1, -0.2, 0.3]])) net.bias.fill_(0.2) fine = t.arange(2 * 3 * 5).float().reshape(1, 2, 3, 5) / 10 coarse = t.arange(7 * 9).float().reshape(7, 9) / 10 expected = feature.predict(net, fine, coarse, "scene_features", chunk=100) actual = feature.predict(net, fine, coarse, "scene_features", chunk=11) t.testing.assert_close(actual, expected) for k in range(4): rotated = feature.predict( net, t.rot90(fine, k, [-2, -1]), t.rot90(coarse, k), "scene_features", chunk=11, ) t.testing.assert_close(t.rot90(rotated, -k), expected, atol=2e-6, rtol=1e-6) a = feature.predict(net, fine, coarse, "coarse_only") b = feature.predict(net, fine * 100, coarse, "coarse_only") assert t.equal(a, b) @pytest.mark.parametrize("arm", ["coarse_only", "scene_features"]) def test_fit_stationarity_weight_scale_duplication_and_chunk_invariance(arm): t, x, c, y, w = tensors() a, report = m.fit(x, c, y, w, arm, chunk=2) b, repeated = m.fit(x.repeat(2, 1), c.repeat(2, 1), y.repeat(2), w.repeat(2) * 9, arm) assert report["converged"] and repeated["converged"] assert report["status"] == "converged" assert report["gradient_inf_norm"] <= 1e-4 assert report["evaluations"] <= 400 assert report["production_eligible"] is False for p, q in zip(a.parameters(), b.parameters(), strict=True): t.testing.assert_close(p, q, atol=1e-4, rtol=1e-4) if arm == "coarse_only": assert t.count_nonzero(a.weight[:, :-1]) == 0 # Independently recompute the full objective and every parameter gradient. logits = a(x, c, arm)[:, 0] per_point = t.nn.functional.binary_cross_entropy_with_logits( logits, y.double(), reduction="none" ) data = (per_point * w).sum() / w.sum() penalty = 0.5 * 0.01 * sum(p.square().sum() for p in a.parameters()) objective = data + penalty objective.backward() grad = max(float(p.grad.abs().max()) for p in a.parameters()) assert float(data) == pytest.approx(report["data_loss"], abs=1e-12) assert float(penalty) == pytest.approx(report["l2_loss"], abs=1e-12) assert float(objective) == pytest.approx(report["loss"], abs=1e-12) assert grad == pytest.approx(report["gradient_inf_norm"], abs=1e-12) assert grad <= 1e-4 def test_bias_is_regularized_even_for_one_class(): t = pytest.importorskip("torch") x, c = t.zeros(8, 2, dtype=t.float64), t.zeros(8, 1, dtype=t.float64) net, report = m.fit(x, c, t.ones(8), t.ones(8, dtype=t.float64)) assert report["converged"] assert 0 < float(net.bias) < 10 assert report["l2_loss"] == pytest.approx(0.005 * float(net.bias.square()), abs=1e-12) assert abs(float(t.sigmoid(net.bias) - 1 + 0.01 * net.bias)) <= 1e-4 @pytest.mark.parametrize("unknown", [-1, 255, 0.5]) @pytest.mark.parametrize("weight", [0., 1.]) def test_unknown_rejected_even_at_zero_weight(unknown, weight): t, x, c, y, w = tensors() y = y.double() y[0], w[0] = unknown, weight with pytest.raises(ValueError, match="binary known"): m.fit(x, c, y, w) @pytest.mark.parametrize( "bad", [ "fine_shape", "coarse_shape", "target_shape", "weight_shape", "empty", "dtype", "fine_nan", "coarse_inf", "target_nan", "weight_nan", "negative_weight", "zero_sum", "input_gradient", "arm", "chunk", ], ) def test_input_validation(bad): t, x, c, y, w = tensors() kwargs = {} if bad == "fine_shape": x = x[None] elif bad == "coarse_shape": c = c[:, 0] elif bad == "target_shape": y = y[:-1] elif bad == "weight_shape": w = w[:-1] elif bad == "empty": x, c, y, w = x[:0], c[:0], y[:0], w[:0] elif bad == "dtype": c = c.float() elif bad == "fine_nan": x[0, 0] = float("nan") elif bad == "coarse_inf": c[0] = float("inf") elif bad == "target_nan": y = y.double() y[0] = float("nan") elif bad == "weight_nan": w[0] = float("nan") elif bad == "negative_weight": w[0] = -1 elif bad == "zero_sum": w.zero_() elif bad == "input_gradient": x.requires_grad_(True) elif bad == "arm": kwargs["arm"] = "location_specific" else: kwargs["chunk"] = 0 with pytest.raises(ValueError): m.fit(x, c, y, w, **kwargs) def test_no_optimizer_progress_is_technical_stop(monkeypatch): t, x, c, y, w = tensors() real = t.optim.LBFGS def stopped(parameters, **kwargs): optimizer = real(parameters, **kwargs) monkeypatch.setattr(optimizer, "step", lambda closure: closure()) return optimizer monkeypatch.setattr(t.optim, "LBFGS", stopped) _, report = m.fit(x, c, y, w) assert not report["converged"] assert report["status"] == "technical_stop" assert report["stop_reason"] == "stationarity_not_met" def test_total_timeout_cannot_be_reported_as_convergence(monkeypatch): _, x, c, y, w = tensors() now = iter([0., 121., 121., 121.]) monkeypatch.setattr(m.time, "monotonic", lambda: next(now, 121.)) net, report = m.fit(x, c, y, w) assert not report["converged"] assert report["stop_reason"] == "fit_timeout" assert report["evaluations"] == 0 assert report["gradient_inf_norm"] is None assert all(float(p.abs().sum()) == 0 for p in net.parameters()) def test_line_search_evaluation_budget_is_enforced(monkeypatch): t, x, c, y, w = tensors() real = t.optim.LBFGS monkeypatch.setattr(m, "MAX_EVAL", 3) def repeated(parameters, **kwargs): optimizer = real(parameters, **kwargs) def step(closure): for _ in range(10): closure() monkeypatch.setattr(optimizer, "step", step) return optimizer monkeypatch.setattr(t.optim, "LBFGS", repeated) _, report = m.fit(x, c, y, w) assert report["status"] == "technical_stop" assert report["stop_reason"] == "evaluation_limit" assert report["evaluations"] == 2