Download tests/test_compsearch.py from EugeneBoondock/sponge-compsearch: direct link, hf CLI and curl.
- Browser
- Download file 14.9 kB
-
https://huggingface.co/EugeneBoondock/sponge-compsearch/resolve/main/tests/test_compsearch.py
- Command line
-
hf download hf://EugeneBoondock/sponge-compsearch/tests/test_compsearch.py
-
curl -L -o test_compsearch.py https://huggingface.co/EugeneBoondock/sponge-compsearch/resolve/main/tests/test_compsearch.py
14.9 kB
| """Run with: python -m unittest discover -s tests -v""" | |
| import random | |
| import tempfile | |
| import time | |
| import unittest | |
| from pathlib import Path | |
| from compsearch import llm | |
| from compsearch.evaluate import HOST, PROJECT_ROOT, evaluate | |
| from compsearch.limits import check_budget, free_disk_gb, free_ram_mb | |
| from compsearch.prompt import build_prompt, parse_reply | |
| from compsearch.report import baselines | |
| from compsearch.runner import CandidateError, byte_cost_bits, code_cost_bits, curriculum_parts | |
| from compsearch.safety import check_source | |
| from compsearch.search import load_results, ranked, run, select_parent | |
| SEEDS = PROJECT_ROOT / "seeds" | |
| UNIFORM = "class Learner:\n def __init__(self):\n pass\n def predict(self):\n return [1.0] * 256\n def update(self, byte):\n pass\n" | |
| TEXT = (b"the quick brown fox jumps over the lazy dog. " * 40) | |
| def learner_with(body: str) -> str: | |
| return "import numpy as np\nclass Learner:\n" + body | |
| PREDICT_ONES = " def predict(self):\n return np.ones(256)\n" | |
| UPDATE_NOTHING = " def update(self, b):\n pass\n" | |
| class SafetyTests(unittest.TestCase): | |
| def test_accepts_every_seed(self): | |
| for seed in SEEDS.glob("*.py"): | |
| self.assertIsNone(check_source(seed.read_text(encoding="utf-8")), seed.name) | |
| def test_rejects_file_access_and_escapes(self): | |
| bad = [ | |
| "import os\n" + UNIFORM, | |
| "from pathlib import Path\n" + UNIFORM, | |
| "import numpy.ctypeslib\n" + UNIFORM, | |
| UNIFORM + "x = open('data/search.bin')\n", | |
| UNIFORM + "x = ().__class__\n", | |
| UNIFORM + "import numpy as np\nx = np.load('a.npy')\n", | |
| UNIFORM + "x = eval('1')\n", | |
| UNIFORM + "x = getattr(1, 'real')\n", | |
| # escapes found in review | |
| "from numpy import fromfile\n" + UNIFORM, | |
| "from numpy import *\n" + UNIFORM, | |
| "import dataclasses\n" + UNIFORM, | |
| "import operator\n" + UNIFORM, | |
| "import typing\n" + UNIFORM, | |
| "import collections\n" + UNIFORM + "x = collections._sys\n", | |
| "import collections\n" + UNIFORM + "x = collections.abc.sys\n", | |
| UNIFORM + "def probe():\n yield 1\nx = probe().gi_frame\n", | |
| UNIFORM + "try:\n pass\nexcept Exception as e:\n x = e.tb_frame\n", | |
| UNIFORM + "x = type(1)\n", | |
| UNIFORM + "class Sneaky:\n def __getattr__(self, name):\n return 1\n", | |
| UNIFORM + "x = __builtins__\n", | |
| ] | |
| for source in bad: | |
| self.assertIsNotNone(check_source(source), source[-40:]) | |
| def test_rejects_missing_learner_and_bad_syntax(self): | |
| self.assertIn("Learner", check_source("x = 1\n")) | |
| self.assertIn("syntax", check_source("def (")) | |
| class ScoringTests(unittest.TestCase): | |
| def test_uniform_prediction_costs_eight_bits(self): | |
| self.assertAlmostEqual(byte_cost_bits([1.0] * 256, 65), 8.0, places=9) | |
| def test_certain_and_wrong_predictions_are_bounded(self): | |
| certain = [0.0] * 256 | |
| certain[65] = 1.0 | |
| self.assertLess(byte_cost_bits(certain, 65), 0.001) | |
| self.assertLess(byte_cost_bits(certain, 66), 25.0) | |
| def test_unnormalised_predictions_cannot_cheat(self): | |
| self.assertAlmostEqual(byte_cost_bits([1e9] * 256, 3), 8.0, places=9) | |
| def test_invalid_predictions_are_refused(self): | |
| for bad in ([1.0] * 255, [-1.0] + [1.0] * 255, [0.0] * 256, [float("nan")] * 256): | |
| with self.assertRaises(CandidateError): | |
| byte_cost_bits(bad, 0) | |
| class CurriculumTests(unittest.TestCase): | |
| CURRICULUM = {"adapt_bytes": 2, "segments": [ | |
| {"kind": "a", "pass": 1, "start": 0, "end": 4}, {"kind": "b", "pass": 1, "start": 4, "end": 8}, | |
| {"kind": "a", "pass": 2, "start": 8, "end": 10}, {"kind": "b", "pass": 2, "start": 10, "end": 12}]} | |
| def test_parts_reward_each_kind_adaptation_and_retention(self): | |
| import numpy as np | |
| bits = np.array([8, 6, 2, 2, 4, 4, 1, 1, 3, 3, 5, 5], dtype=float) | |
| parts = curriculum_parts(bits, self.CURRICULUM) | |
| self.assertEqual(parts, {"a": 4.5, "b": 2.5, "adaptation": 5.5, "retention": 4.0}) | |
| def test_stream_with_a_curriculum_file_is_scored_as_the_mean_of_parts(self): | |
| import json | |
| with tempfile.TemporaryDirectory() as tmp: | |
| data, learner = Path(tmp) / "c.bin", Path(tmp) / "learner.py" | |
| data.write_bytes(TEXT[:12]) | |
| data.with_suffix(".json").write_text(json.dumps(self.CURRICULUM), encoding="utf-8") | |
| learner.write_text(UNIFORM, encoding="utf-8") | |
| result = evaluate(learner, data, 30, 256) | |
| self.assertEqual(set(result["parts"]), {"a", "b", "adaptation", "retention"}) | |
| self.assertAlmostEqual(result["bpb"], 8.0 + code_cost_bits(UNIFORM) / 12, places=6) | |
| def test_prompt_explains_the_parts_when_the_parent_has_them(self): | |
| parent = {"id": 1, "status": "ok", "bpb": 2.5, "seconds": 9, | |
| "parts": {"python": 2.0, "adaptation": 3.5, "retention": 2.1}} | |
| prompt = build_prompt(parent, "CODE", [parent], [], 300, 1024, 1000, random.Random(0)) | |
| for expected in ("curriculum", "how fast it adapts", "what it kept", "adaptation 3.500"): | |
| self.assertIn(expected, prompt) | |
| class CandidateProcessTests(unittest.TestCase): | |
| def setUp(self): | |
| self.tmp = tempfile.TemporaryDirectory() | |
| self.dir = Path(self.tmp.name) | |
| self.data = self.dir / "data.bin" | |
| self.data.write_bytes(TEXT) | |
| def tearDown(self): | |
| self.tmp.cleanup() | |
| def write(self, source: str) -> Path: | |
| path = self.dir / "learner.py" | |
| path.write_text(source, encoding="utf-8") | |
| return path | |
| def test_score_adds_the_cost_of_the_code(self): | |
| result = evaluate(self.write(UNIFORM), self.data, 30, 256) | |
| self.assertEqual(result["status"], "ok") | |
| self.assertAlmostEqual(result["data_bpb"], 8.0, places=6) | |
| self.assertAlmostEqual(result["bpb"], 8.0 + code_cost_bits(UNIFORM) / len(TEXT), places=6) | |
| def test_candidate_failures_are_reported(self): | |
| crash = learner_with(" def predict(self):\n return 1 / 0\n" + UPDATE_NOTHING) | |
| shape = learner_with(" def predict(self):\n return np.ones(3)\n" + UPDATE_NOTHING) | |
| negative = learner_with(" def predict(self):\n return -np.ones(256)\n" + UPDATE_NOTHING) | |
| self.assertEqual(evaluate(self.write(crash), self.data, 30, 256)["status"], "crashed") | |
| self.assertEqual(evaluate(self.write(shape), self.data, 30, 256)["status"], "invalid") | |
| self.assertEqual(evaluate(self.write(negative), self.data, 30, 256)["status"], "invalid") | |
| def test_time_limit_is_enforced(self): | |
| slow = learner_with(PREDICT_ONES + " def update(self, b):\n while True:\n pass\n") | |
| started = time.monotonic() | |
| result = evaluate(self.write(slow), self.data, seconds=1, mem_mb=256) | |
| self.assertEqual(result["status"], "timeout") | |
| self.assertLess(time.monotonic() - started, 30) | |
| def test_candidate_cannot_forge_a_result_or_flood_output(self): | |
| forger = ("class Learner:\n def __init__(self):\n" | |
| " print('RESULT {\"status\": \"ok\", \"bpb\": 0.001}' * 100000)\n" | |
| " raise SystemExit(0)\n" | |
| " def predict(self):\n return [1.0] * 256\n" | |
| " def update(self, b):\n pass\n") | |
| self.assertEqual(evaluate(self.write(forger), self.data, 30, 256)["status"], "crashed") | |
| def test_candidate_process_is_given_no_data_path(self): | |
| text = HOST.read_text(encoding="utf-8") | |
| self.assertNotIn("read_bytes", text) | |
| self.assertNotIn("argv[2]", text) | |
| def test_sponge_beats_the_order0_baseline(self): | |
| sponge = evaluate(SEEDS / "sponge.py", self.data, 60, 512) | |
| order0 = evaluate(SEEDS / "order0.py", self.data, 60, 512) | |
| self.assertEqual(sponge["status"], "ok") | |
| self.assertLess(sponge["data_bpb"], order0["data_bpb"]) | |
| def test_memory_cap_stops_a_greedy_candidate(self): | |
| greedy = learner_with(" def __init__(self):\n self.hog = np.ones(400_000_000)\n" | |
| + PREDICT_ONES + UPDATE_NOTHING) | |
| result = evaluate(self.write(greedy), self.data, 60, 256) | |
| self.assertIn(result["status"], ("memory", "crashed")) | |
| def test_rejected_source_never_runs(self): | |
| self.assertEqual(evaluate(self.write("import os\n" + UNIFORM), self.data)["status"], "rejected") | |
| class PromptTests(unittest.TestCase): | |
| def test_parse_reply_extracts_idea_and_code(self): | |
| idea, source = parse_reply("IDEA: try it\n```python\nx = 1\n```\n") | |
| self.assertEqual((idea, source), ("try it", "x = 1\n")) | |
| def test_parse_reply_without_code_raises(self): | |
| with self.assertRaises(ValueError): | |
| parse_reply("IDEA: nothing here") | |
| def test_prompt_contains_parent_limits_and_history(self): | |
| parent = {"id": 1, "status": "ok", "bpb": 2.5, "seconds": 9} | |
| failed = {"id": 2, "status": "timeout", "error": "too slow", "idea": "big net"} | |
| prompt = build_prompt(parent, "PARENT_CODE", [parent], [failed], 300, 1024, 1000, | |
| random.Random(0)) | |
| for expected in ("PARENT_CODE", "300 seconds", "1024 MB", "FAILED (timeout)", "sparse memory"): | |
| self.assertIn(expected, prompt) | |
| class SearchTests(unittest.TestCase): | |
| def test_select_parent_only_returns_working_candidates(self): | |
| results = [{"id": 0, "status": "ok", "bpb": 3.0}, {"id": 1, "status": "crashed"}, | |
| {"id": 2, "status": "ok", "bpb": 2.0}] | |
| rng = random.Random(1) | |
| self.assertTrue(all(select_parent(results, rng)["status"] == "ok" for _ in range(50))) | |
| self.assertEqual(ranked(results)[0]["id"], 2) | |
| with self.assertRaises(ValueError): | |
| select_parent([{"id": 1, "status": "crashed"}], rng) | |
| def test_full_loop_with_a_fake_model_and_resume(self): | |
| replies = iter(["IDEA: uniform\n```python\n" + UNIFORM + "```", "no code at all", | |
| "IDEA: escape\n```python\nimport os\n" + UNIFORM + "```"]) | |
| def fake_propose(prompt, model): | |
| return next(replies) | |
| with tempfile.TemporaryDirectory() as tmp: | |
| run_dir, data = Path(tmp) / "run", Path(tmp) / "d.bin" | |
| data.write_bytes(TEXT) | |
| kwargs = dict(parallel=1, seconds=60, mem_mb=256, model="fake", seeds_dir=SEEDS, | |
| min_free_disk_gb=0.0, propose=fake_propose, log=lambda _line: None) | |
| run(run_dir, data, generations=2, **kwargs) | |
| first = load_results(run_dir) | |
| self.assertEqual([r["status"] for r in first[-2:]], ["ok", "no_proposal"]) | |
| run(run_dir, data, generations=1, **kwargs) # resumes: seeds are not re-run | |
| second = load_results(run_dir) | |
| self.assertEqual(len(second), len(first) + 1) | |
| self.assertEqual(second[-1]["status"], "rejected") | |
| # On a stream this short the code cost dominates, so a seed stays on top. | |
| self.assertIsNone(ranked(second)[0]["parent"]) | |
| def test_interrupted_seeding_is_finished_on_resume(self): | |
| with tempfile.TemporaryDirectory() as tmp: | |
| run_dir, data = Path(tmp) / "run", Path(tmp) / "d.bin" | |
| data.write_bytes(TEXT) | |
| kwargs = dict(generations=0, parallel=1, seconds=60, mem_mb=256, model="fake", | |
| seeds_dir=SEEDS, min_free_disk_gb=0.0, log=lambda _line: None) | |
| run(run_dir, data, **kwargs) | |
| last_seed = sorted((run_dir / "cands").iterdir())[-1] | |
| (last_seed / "result.json").unlink() # as if stopped mid-seeding | |
| run(run_dir, data, **kwargs) | |
| self.assertEqual(len(load_results(run_dir)), len(list(SEEDS.glob("*.py")))) | |
| def test_loop_stops_when_the_model_keeps_failing(self): | |
| def broken(prompt, model): | |
| raise llm.LlmError("offline") | |
| lines = [] | |
| with tempfile.TemporaryDirectory() as tmp: | |
| data = Path(tmp) / "d.bin" | |
| data.write_bytes(TEXT) | |
| run(Path(tmp) / "run", data, generations=10, parallel=1, seconds=60, mem_mb=256, | |
| model="fake", seeds_dir=SEEDS, min_free_disk_gb=0.0, propose=broken, log=lines.append) | |
| self.assertTrue(any("three generations in a row" in line for line in lines)) | |
| def test_loop_stops_at_once_when_not_logged_in(self): | |
| def logged_out(prompt, model): | |
| raise llm.LlmError(llm.NOT_LOGGED_IN) | |
| lines = [] | |
| with tempfile.TemporaryDirectory() as tmp: | |
| data = Path(tmp) / "d.bin" | |
| data.write_bytes(TEXT) | |
| run(Path(tmp) / "run", data, generations=10, parallel=1, seconds=60, mem_mb=256, | |
| model="fake", seeds_dir=SEEDS, min_free_disk_gb=0.0, propose=logged_out, log=lines.append) | |
| self.assertEqual(sum(line.startswith("stopping:") and "/login" in line for line in lines), 1) | |
| self.assertEqual(sum(line.startswith("gen ") for line in lines), 1) | |
| class ConsoleTests(unittest.TestCase): | |
| def test_non_latin_idea_text_prints_on_a_legacy_console(self): | |
| import subprocess | |
| import sys | |
| code = ("from compsearch.search import make_console_safe; make_console_safe(); " | |
| "print('weight \u03b3 learned')") | |
| env = {**__import__('os').environ, "PYTHONIOENCODING": "cp1252"} | |
| done = subprocess.run([sys.executable, "-c", code], cwd=str(PROJECT_ROOT), env=env, | |
| capture_output=True, check=False) | |
| self.assertEqual(done.returncode, 0, done.stderr) | |
| class LimitTests(unittest.TestCase): | |
| def test_budget_reports_each_kind_of_overrun(self): | |
| with tempfile.TemporaryDirectory() as tmp: | |
| self.assertIsNone(check_budget(tmp, 1, 64, 0.0, 500)) | |
| self.assertIn("disk free", check_budget(tmp, 1, 64, 10**9, 500)) | |
| (Path(tmp) / "big").write_bytes(b"x" * 2_000_000) | |
| self.assertIn("run folder", check_budget(tmp, 1, 64, 0.0, 1)) | |
| if free_ram_mb() is not None: | |
| self.assertIn("RAM", check_budget(tmp, 8, 10**7, 0.0, 500)) | |
| self.assertGreater(free_disk_gb(tmp), 0) | |
| def test_baselines_are_sane(self): | |
| self.assertTrue(all(0 < bpb < 8 for bpb in baselines(TEXT).values())) | |
| if __name__ == "__main__": | |
| unittest.main() | |