mirror of
https://github.com/elder-plinius/OBLITERATUS.git
synced 2026-12-06 11:04:06 +01:00
Finish the measurement-validity audit for the two remaining geometry modules. wasserstein_transfer: - The Gaussian W2 paired sorted eigenvalues and underestimated the distance for non-commuting covariances (0 for a 45-degree rotation of diag(100, 1)). Compute the exact closed form with a stable PSD square root, from each side's own mean and covariance. - Mismatched widths gave a truncated value and failures gave 0; both are now None with a reason. Failed map inversion no longer falls back to the raw cross-covariance. Fidelity is exact Pearson correlation. - The "transport map" is a ridge least-squares map, not a Gaussian Monge map. Viability, fidelity and recommendations are labelled heuristics and are None unless their inputs exist; refusal-removal estimates that measured nothing are unsupported and always None. bayesian_kernel_projection: - Relabel as seeded random search with local perturbation over a partial linear projection (no surrogate or kernel). The Pareto front could keep a dominated trial on reduction ties; fixed. With no signal or no input, best results are None with a reason instead of score 0. Both modules now carry measurement evidence and catalog rows checked by the registry test, and the app overview no longer claims a Monge map or TPE optimization. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
141 lines
6.8 KiB
Python
141 lines
6.8 KiB
Python
"""Executable registry: every audited geometry field has evidence and a catalog row."""
|
|
|
|
import re
|
|
from dataclasses import fields
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
import torch
|
|
|
|
from obliteratus.analysis.bayesian_kernel_projection import (
|
|
BayesianKernelProjection,
|
|
BayesianOptimizationResult,
|
|
ProjectionConfig,
|
|
TrialResult,
|
|
)
|
|
from obliteratus.analysis.concept_geometry import ConceptConeAnalyzer, ConeConeResult, MultiLayerConeResult
|
|
from obliteratus.analysis.cross_layer import CrossLayerAlignmentAnalyzer, CrossLayerResult
|
|
from obliteratus.analysis.leace import LEACEExtractor, LEACEResult
|
|
from obliteratus.analysis.leace_exact import ExactLEACEExtractor, ExactLEACEResult
|
|
from obliteratus.analysis.wasserstein_optimal import (
|
|
MultiLayerWassersteinResult,
|
|
WassersteinComparisonResult,
|
|
WassersteinDirectionResult,
|
|
WassersteinOptimalExtractor,
|
|
)
|
|
from obliteratus.analysis.wasserstein_transfer import (
|
|
TransferredDirection,
|
|
TransportPlan,
|
|
WassersteinRefusalTransfer,
|
|
WassersteinTransferResult,
|
|
)
|
|
from obliteratus.concepts.extraction import LayerExtraction
|
|
|
|
pytestmark = pytest.mark.cpu
|
|
|
|
DOC = Path(__file__).resolve().parents[1] / "docs" / "geometry-measurement-validity.md"
|
|
STRUCTURAL = {"layer_idx", "measurement_evidence"}
|
|
STATUSES = {"diagnostic", "unsupported", "unavailable"}
|
|
|
|
|
|
def catalog_rows(heading):
|
|
text = DOC.read_text(encoding="utf-8")
|
|
match = re.search(rf"^###+ {re.escape(heading)}\b.*?$(.*?)(?=^##)", text, re.M | re.S)
|
|
assert match, f"catalog section missing for {heading}"
|
|
return set(re.findall(r"^\| `([a-z_]+)` \|", match.group(1), re.M))
|
|
|
|
|
|
def reported(cls):
|
|
return {f.name for f in fields(cls)} - STRUCTURAL
|
|
|
|
|
|
def results():
|
|
harmful = [torch.tensor([1., 0., 0.]), torch.tensor([1., 0., 0.]), torch.tensor([0., 1., 0.]), torch.tensor([0., 1., 0.])]
|
|
harmless = [torch.zeros(3)] * 4
|
|
cones = ConceptConeAnalyzer(category_map={0: "a", 1: "a", 2: "b", 3: "b"})
|
|
sparse = [torch.zeros(3)] * 4
|
|
extractor = WassersteinOptimalExtractor()
|
|
shifted = [h + torch.tensor([0., 0., 1.]) for h in harmful]
|
|
wasserstein = extractor.extract(shifted, harmful)
|
|
leace_harmful = [torch.tensor([2., 0., 1.]), torch.tensor([3., 1., 0.]), torch.tensor([4., -1., 1.])]
|
|
leace_harmless = [-h for h in leace_harmful]
|
|
gen = torch.Generator().manual_seed(0)
|
|
src = torch.randn(10, 3, generator=gen)
|
|
transfer = WassersteinRefusalTransfer()
|
|
transferred = transfer.compute_transfer({0: src}, {0: src @ torch.randn(3, 3, generator=gen)}, {0: torch.ones(3)})
|
|
cross_width = transfer.compute_transfer({0: src}, {0: torch.randn(10, 4, generator=gen)}, {0: torch.ones(3)})
|
|
search = BayesianKernelProjection(n_trials=3).optimize({0: harmful}, {0: harmless}, {0: torch.eye(3)[:2]})
|
|
return [
|
|
transferred, cross_width, transfer.compute_transfer({}, {}, {}),
|
|
transferred.transferred_directions[0], cross_width.transferred_directions[0],
|
|
transfer._compute_transport_plan(src, src + 1, "a", "b"),
|
|
search, search.all_trials[0], BayesianKernelProjection(n_trials=1).optimize({}, {}, {}),
|
|
cones.analyze_layer(harmful, harmless), cones.analyze_layer(sparse, sparse),
|
|
cones.analyze_all_layers({0: harmful}, {0: harmless}), cones.analyze_all_layers({}, {}),
|
|
CrossLayerAlignmentAnalyzer().analyze({0: torch.ones(3), 1: torch.tensor([1., 0., 0.])}),
|
|
CrossLayerAlignmentAnalyzer().analyze({}),
|
|
LEACEExtractor().extract(leace_harmful, leace_harmless),
|
|
ExactLEACEExtractor().extract(leace_harmful, leace_harmless),
|
|
wasserstein, extractor.extract(harmful, harmful),
|
|
extractor.compare_with_alternatives(wasserstein, shifted, harmful),
|
|
extractor.extract_all_layers({0: shifted}, {0: harmful}),
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize("result", results(), ids=lambda r: type(r).__name__)
|
|
def test_every_reported_field_has_complete_evidence(result):
|
|
assert set(result.measurement_evidence) == reported(type(result))
|
|
for name, evidence in result.measurement_evidence.items():
|
|
assert evidence.definition and evidence.units and evidence.assumptions and evidence.scope, name
|
|
assert evidence.status in STATUSES
|
|
assert (evidence.status == "diagnostic") == (evidence.unavailable_reason is None), name
|
|
value = getattr(result, name)
|
|
if value is None:
|
|
assert evidence.status != "diagnostic", f"{name} is None but labelled diagnostic"
|
|
|
|
|
|
@pytest.mark.parametrize("heading, classes", [
|
|
("ConeConeResult", [ConeConeResult]),
|
|
("MultiLayerConeResult", [MultiLayerConeResult]),
|
|
("CrossLayerResult", [CrossLayerResult]),
|
|
("LEACEResult", [LEACEResult]),
|
|
("ExactLEACEResult", [ExactLEACEResult]),
|
|
("LayerExtraction", [LayerExtraction]),
|
|
("Wasserstein-optimal results", [WassersteinDirectionResult, WassersteinComparisonResult, MultiLayerWassersteinResult]),
|
|
("TransportPlan", [TransportPlan]),
|
|
("TransferredDirection", [TransferredDirection]),
|
|
("WassersteinTransferResult", [WassersteinTransferResult]),
|
|
("ProjectionConfig", [ProjectionConfig]),
|
|
("TrialResult", [TrialResult]),
|
|
("BayesianOptimizationResult", [BayesianOptimizationResult]),
|
|
])
|
|
def test_every_reported_field_has_a_catalog_row(heading, classes):
|
|
rows = catalog_rows(heading)
|
|
expected = set().union(*(reported(cls) for cls in classes))
|
|
assert expected <= rows, f"missing catalog rows: {sorted(expected - rows)}"
|
|
assert rows <= expected | {"cosine_similarity", "cosine_similarity_available", "leace_eigenvalue", "leace_erasure_loss"}
|
|
|
|
|
|
def test_comparison_dictionary_keys_have_catalog_rows():
|
|
result = LEACEExtractor().extract([torch.ones(2), torch.zeros(2)], [-torch.ones(2), torch.zeros(2)])
|
|
keys = set(LEACEExtractor.compare_with_diff_of_means(result, torch.ones(2), torch.zeros(2)))
|
|
assert keys <= catalog_rows("LEACEResult")
|
|
|
|
|
|
def test_caller_constructed_results_carry_no_evidence():
|
|
legacy = CrossLayerResult(torch.eye(1), [0], [[0]], [0.0], 0.0, 1.0, 1.0, 1)
|
|
assert legacy.measurement_evidence == {}
|
|
|
|
|
|
@pytest.mark.parametrize("heading", ["TransportPlan", "TransferredDirection", "WassersteinTransferResult",
|
|
"BayesianOptimizationResult"])
|
|
def test_catalog_marks_the_same_fields_heuristic_as_the_code(heading):
|
|
"""A row whose status column starts with "Heuristic" matches a code definition that does."""
|
|
text = DOC.read_text(encoding="utf-8")
|
|
section = re.search(rf"^###+ {heading}\b.*?$(.*?)(?=^##)", text, re.M | re.S).group(1)
|
|
# The status column is the last cell; definitions may contain |x| norms.
|
|
doc = set(re.findall(r"^\| `([a-z_]+)` \|.*\| Heuristic[^|]*\|$", section, re.M))
|
|
result = next(r for r in results() if type(r).__name__ == heading)
|
|
code = {n for n, e in result.measurement_evidence.items() if e.definition.startswith("Heuristic")}
|
|
assert doc == code
|