import numpy as np import pytest from spectra_moe.cli import main from spectra_moe.eval.metrics import ( kl_divergence, logit_kl, retention, routing_agreement, softmax, ) def test_budget_command_runs(capsys): assert main(["budget"]) == 0 out = capsys.readouterr().out assert "kimi-k3" in out and "structural" in out.lower() or "reduction" in out.lower() def test_analyze_command_on_surrogate(capsys): assert main(["analyze", "--limit", "3"]) == 0 assert "MP bulk" in capsys.readouterr().out def test_compress_command(tmp_path, capsys): rc = main(["compress", "--layers", "1", "--experts", "8", "--rows", "32", "--cols", "32", "--tokens", "200", "--out", str(tmp_path / "m.spectra")]) assert rc == 0 assert "compression report" in capsys.readouterr().out def test_inspect_command(tmp_path, capsys): main(["compress", "--layers", "1", "--experts", "8", "--rows", "32", "--cols", "32", "--tokens", "200", "--out", str(tmp_path / "m.spectra")]) capsys.readouterr() assert main(["inspect", str(tmp_path / "m.spectra"), "--verify"]) == 0 assert "resident_gib" in capsys.readouterr().out def test_misscurve_command(capsys): rc = main(["misscurve", "--experts", "32", "--tokens", "300", "--sizes", "4", "16", "--locality", "0.2", "0.9"]) assert rc == 0 assert "hit rate" in capsys.readouterr().out def test_retention_is_chance_corrected(): teacher, student, chance = {"a": 0.8}, {"a": 0.6}, {"a": 0.25} assert retention(student, teacher, chance) == pytest.approx((0.6 - 0.25) / (0.8 - 0.25)) def test_retention_of_identical_model_is_one(): t = {"a": 0.8, "b": 0.5} assert retention(t, t) == pytest.approx(1.0) def test_kl_zero_for_identical_distributions(): p = softmax(np.random.default_rng(0).normal(size=(5, 7))) assert kl_divergence(p, p) == pytest.approx(0.0, abs=1e-12) def test_logit_kl_positive_for_different_logits(): rng = np.random.default_rng(1) assert logit_kl(rng.normal(size=(8, 12)), rng.normal(size=(8, 12))) > 0 def test_routing_agreement_bounds(): r = np.array([[1, 2, 3], [4, 5, 6]]) assert routing_agreement(r, r) == pytest.approx(1.0) assert routing_agreement(r, np.array([[7, 8, 9], [10, 11, 12]])) == pytest.approx(0.0)