From 71c56c77f0c803aabe479011514ec88a2eaac1ba Mon Sep 17 00:00:00 2001 From: Sau1707 <83017316+Sau1707@users.noreply.github.com> Date: Tue, 10 Nov 2026 18:06:59 +0100 Subject: [PATCH] perf: Batch benchmark inference and cache baseline results --- .github/workflows/model.yml | 23 +++- model/benchmark/src/evaluate.py | 40 ++++-- model/benchmark/src/inference.py | 20 ++- model/benchmark/src/settings.py | 1 + model/benchmark/src/trial.py | 6 +- model/benchmark/tests/test_evaluate.py | 37 ++++- model/benchmark/tests/test_inference.py | 16 ++- model/benchmark/tests/test_trial.py | 65 ++++++++- model/cache.py | 120 ++++++++++++++++ model/ci.py | 1 + model/tests/test_cache.py | 176 ++++++++++++++++++++++++ 11 files changed, 475 insertions(+), 30 deletions(-) create mode 100644 model/cache.py create mode 100644 model/tests/test_cache.py diff --git a/.github/workflows/model.yml b/.github/workflows/model.yml index d98fc30..661f33a 100644 --- a/.github/workflows/model.yml +++ b/.github/workflows/model.yml @@ -81,12 +81,33 @@ jobs: env: PYTHONPATH: src/api/src run: uv run --project model/benchmark --locked --extra cuda --extra data --python 3.12 pytest model/benchmark/tests + - name: Fingerprint accepted-model evaluation + id: baseline-key + if: env.BOOTSTRAP == '' + run: uv run --project model/benchmark --locked --extra cuda --extra data --python 3.12 python -m model.cache key --directory "$RUN_DIR" + - uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5 + id: baseline-cache + if: env.BOOTSTRAP == '' + with: + path: .baseline-cache + key: ${{ steps.baseline-key.outputs.key }} + - name: Restore accepted-model evaluation + if: env.BOOTSTRAP == '' && steps.baseline-cache.outputs.cache-hit == 'true' + run: uv run --project model/benchmark --locked --extra cuda --extra data --python 3.12 python -m model.cache restore --directory "$RUN_DIR" - name: Evaluate accepted model with current benchmark - if: github.event_name != 'workflow_dispatch' || !inputs.bootstrap + if: env.BOOTSTRAP == '' && steps.baseline-cache.outputs.cache-hit != 'true' run: >- uv run --project model/benchmark --locked --extra cuda --extra data --python 3.12 python model/ci.py evaluate --directory "$RUN_DIR" --adapter baseline --output baseline.jsonl + - name: Store accepted-model evaluation + if: github.ref == 'refs/heads/main' && env.BOOTSTRAP == '' && steps.baseline-cache.outputs.cache-hit != 'true' + run: uv run --project model/benchmark --locked --extra cuda --extra data --python 3.12 python -m model.cache store --directory "$RUN_DIR" + - uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5 + if: github.ref == 'refs/heads/main' && env.BOOTSTRAP == '' && steps.baseline-cache.outputs.cache-hit != 'true' + with: + path: .baseline-cache + key: ${{ steps.baseline-key.outputs.key }} - name: Evaluate candidate with current benchmark run: >- uv run --project model/benchmark --locked --extra cuda --extra data --python 3.12 diff --git a/model/benchmark/src/evaluate.py b/model/benchmark/src/evaluate.py index a08b944..7092eb4 100644 --- a/model/benchmark/src/evaluate.py +++ b/model/benchmark/src/evaluate.py @@ -1,6 +1,6 @@ import json from pathlib import Path -from contextlib import closing +from contextlib import ExitStack, closing from model.benchmark.src.trial import trial from model.benchmark.src.settings import Settings from model.benchmark.src.execution import Worker @@ -19,11 +19,35 @@ def run(config: Settings) -> None: generate = HFCompletion(config) config.output.parent.mkdir(parents=True, exist_ok=True) passed = 0 - with config.output.open("x") as file, closing(Worker()) as worker: - for index, record in enumerate(records, 1): - row = trial(worker, record, generate, config.calls) - file.write(json.dumps(row) + "\n") - file.flush() - passed += row["status"] == "passed" - print(f"{index}/{len(records)}: {record['id']} {row['status']}", flush=True) + with config.output.open("x") as file, ExitStack() as stack: + workers = [] + for _ in range(min(config.batch_size, len(records))): + worker = Worker() + workers.append(stack.enter_context(closing(worker))) + remaining = iter(records) + active = [] + for worker in workers: + task = trial(worker, next(remaining), config.calls) + active.append((worker, task, next(task))) + completed = 0 + while active: + completions = generate([prompt for _, _, prompt in active]) + pending = [] + for (worker, task, _), completion in zip(active, completions, strict=True): + try: + prompt = task.send(completion) + except StopIteration as result: + row = result.value + file.write(json.dumps(row) + "\n") + file.flush() + passed += row["status"] == "passed" + completed += 1 + print(f"{completed}/{len(records)}: {row['id']} {row['status']}", flush=True) + record = next(remaining, None) + if record is None: + continue + task = trial(worker, record, config.calls) + prompt = next(task) + pending.append((worker, task, prompt)) + active = pending print(f"Passed {passed}/{len(records)} ({passed / len(records):.1%})", flush=True) diff --git a/model/benchmark/src/inference.py b/model/benchmark/src/inference.py index 64a7ea9..3f6fb6c 100644 --- a/model/benchmark/src/inference.py +++ b/model/benchmark/src/inference.py @@ -2,6 +2,7 @@ import torch from peft import PeftModel from transformers import AutoTokenizer, StopStringCriteria, StoppingCriteriaList, AutoModelForImageTextToText +from collections.abc import Sequence from pyshell.parsing import parse_completion from pyshell.serialization import MARKERS from model.benchmark.src.settings import Settings @@ -19,15 +20,18 @@ def __init__(self, config: Settings) -> None: torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False self.tokenizer = AutoTokenizer.from_pretrained(base, revision=revision) + self.tokenizer.padding_side = "left" + if self.tokenizer.pad_token_id is None: + self.tokenizer.pad_token = self.tokenizer.eos_token self.model = AutoModelForImageTextToText.from_pretrained(base, revision=revision, dtype=torch.float32, attn_implementation="sdpa") self.model = PeftModel.from_pretrained(self.model, config.adapter) self.model.to(config.device).eval() self.max_new_tokens = config.tokens self.stopping_criteria = StoppingCriteriaList([StopStringCriteria(self.tokenizer, list(MARKERS))]) - def __call__(self, prompt: str) -> tuple[str, bool]: - """Return generated code and whether its closing marker was reached.""" - inputs = self.tokenizer(prompt, return_tensors="pt", add_special_tokens=False).to(self.model.device) + def __call__(self, prompts: Sequence[str]) -> list[tuple[str, bool]]: + """Return generated code and boundary status for each prompt.""" + inputs = self.tokenizer(list(prompts), return_tensors="pt", add_special_tokens=False, padding=True).to(self.model.device) with torch.inference_mode(): output = self.model.generate( **inputs, @@ -37,5 +41,11 @@ def __call__(self, prompt: str) -> tuple[str, bool]: stop_strings=None, stopping_criteria=self.stopping_criteria, ) - text = self.tokenizer.decode(output[0, inputs.input_ids.shape[1] :], skip_special_tokens=False) - return parse_completion(text) + eos = self.model.generation_config.eos_token_id + eos = set(eos if isinstance(eos, list) else [eos]) + completions = [] + for tokens in output[:, inputs.input_ids.shape[1] :].tolist(): + end = next((index + 1 for index, token in enumerate(tokens) if token in eos), len(tokens)) + text = self.tokenizer.decode(tokens[:end], skip_special_tokens=False) + completions.append(parse_completion(text)) + return completions diff --git a/model/benchmark/src/settings.py b/model/benchmark/src/settings.py index 4c1508f..9fc70ee 100644 --- a/model/benchmark/src/settings.py +++ b/model/benchmark/src/settings.py @@ -22,6 +22,7 @@ class Settings(BaseModel): device: Literal["cpu", "cuda"] = "cpu" tokens: int = Field(default=384, gt=0) threads: int = Field(default=16, gt=0) + batch_size: int = Field(default=1, gt=0) SETTINGS = Settings() diff --git a/model/benchmark/src/trial.py b/model/benchmark/src/trial.py index 35cef5e..0089985 100644 --- a/model/benchmark/src/trial.py +++ b/model/benchmark/src/trial.py @@ -1,10 +1,10 @@ from typing import Any -from collections.abc import Callable +from collections.abc import Generator from pyshell.serialization import Prompt from model.benchmark.src.execution import Worker -def trial(worker: Worker, record: dict[str, Any], generate: Callable[[str], tuple[str, bool]], calls: int) -> dict[str, Any]: +def trial(worker: Worker, record: dict[str, Any], calls: int) -> Generator[str, tuple[str, bool], dict[str, Any]]: """Execute and grade one task within its model-call budget.""" setup = worker.execute(record["setup"], "reset") if setup["exception"]: @@ -19,7 +19,7 @@ def trial(worker: Worker, record: dict[str, Any], generate: Callable[[str], tupl worker.execute("saved_result = result") prompt.append({"role": "user", "content": stage["instruction"]}) for _ in range(calls): - source, ended = generate(prompt.render()) + source, ended = yield prompt.render() step = {"source": source} row["steps"].append(step) if not ended or not source.strip(): diff --git a/model/benchmark/tests/test_evaluate.py b/model/benchmark/tests/test_evaluate.py index 2245b2c..c08ed1e 100644 --- a/model/benchmark/tests/test_evaluate.py +++ b/model/benchmark/tests/test_evaluate.py @@ -21,7 +21,13 @@ def benchmark(tmp_path, monkeypatch): rows = [ {**record, "status": status, "steps": []} for record, status in zip(records, ("passed", "incorrect", "call_limit"), strict=True) ] - monkeypatch.setattr(evaluate, "trial", Mock(side_effect=rows)) + + def task(worker, record, calls): + yield record["id"] + return rows[int(record["id"])] + + monkeypatch.setattr(evaluate, "trial", task) + model.return_value.side_effect = lambda prompts: [("code", True)] * len(prompts) return config, model, worker, rows @@ -53,14 +59,39 @@ def test_empty_tasks_are_rejected_before_loading_model(benchmark): def test_failure_preserves_completed_rows_and_closes_worker(benchmark, monkeypatch): - config, _, worker, rows = benchmark - monkeypatch.setattr(evaluate, "trial", Mock(side_effect=[rows[0], RuntimeError("generation failed")])) + config, model, worker, rows = benchmark + model.return_value.side_effect = [[("code", True)], RuntimeError("generation failed")] with pytest.raises(RuntimeError, match="generation failed"): evaluate.run(config) assert [json.loads(line) for line in config.output.read_text().splitlines()] == rows[:1] worker.return_value.close.assert_called_once_with() +def test_batch_uses_separate_workers_and_closes_all_on_failure(benchmark): + config, model, worker, _ = benchmark + config = config.model_copy(update={"batch_size": 4}) + workers = [Mock() for _ in range(3)] + worker.side_effect = workers + model.return_value.side_effect = RuntimeError("generation failed") + with pytest.raises(RuntimeError, match="generation failed"): + evaluate.run(config) + assert model.return_value.call_args.args == (["0", "1", "2"],) + for instance in workers: + instance.close.assert_called_once_with() + + +def test_batch_evaluates_tail_smaller_than_batch_size(benchmark): + config, model, worker, rows = benchmark + config = config.model_copy(update={"batch_size": 2}) + workers = [Mock(), Mock()] + worker.side_effect = workers + evaluate.run(config) + assert [json.loads(line) for line in config.output.read_text().splitlines()] == rows + assert [call.args[0] for call in model.return_value.call_args_list] == [["0", "1"], ["2"]] + for instance in workers: + instance.close.assert_called_once_with() + + def test_missing_local_benchmark_is_rejected_before_loading_model(benchmark): config, model, _, _ = benchmark missing = config.model_copy(update={"data": str(config.output.parent / "missing")}) diff --git a/model/benchmark/tests/test_inference.py b/model/benchmark/tests/test_inference.py index 089f4df..7baf5fa 100644 --- a/model/benchmark/tests/test_inference.py +++ b/model/benchmark/tests/test_inference.py @@ -19,6 +19,7 @@ def setup(self, tmp_path): self.tokenizer = MagicMock() self.tokenizer.return_value = BatchEncoding({"input_ids": torch.tensor([[1, 2]])}) self.model = MagicMock(device=torch.device("cpu")) + self.model.generation_config.eos_token_id = 99 self.model.generate.return_value = torch.tensor([[1, 2, 3, 4]]) self.model.to.return_value = self.model @@ -52,7 +53,7 @@ def test_adapter_loads_its_recorded_base_model(self, revision): def test_configured_generation_budget_is_used(self): completion = self.completion(max_new_tokens=77) self.tokenizer.decode.return_value = "result = 1" + END_CODE - completion("prompt") + completion(["prompt"]) assert self.model.generate.call_args.kwargs["max_new_tokens"] == 77 @pytest.mark.parametrize("device", ["cpu", "cuda"]) @@ -66,7 +67,7 @@ def test_boundary_matcher_is_built_once_and_reused_across_requests(self): completion = self.completion() self.tokenizer.decode.return_value = "result = 1\n" + END_CODE for _ in range(2): - assert completion("prompt") == ("result = 1\n", True) + assert completion(["prompt"]) == [("result = 1\n", True)] options = self.model.generate.call_args.kwargs assert options["stopping_criteria"] is completion.stopping_criteria assert options["stop_strings"] is None @@ -76,7 +77,16 @@ def test_boundary_matcher_is_built_once_and_reused_across_requests(self): def test_decoded_completion_is_parsed(self): completion = self.completion() self.tokenizer.decode.return_value = "code" + TASK + END_CODE - assert completion("prompt") == ("code", False) + assert completion(["prompt"]) == [("code", False)] + + def test_batch_decoding_removes_padding_after_each_rows_eos(self): + completion = self.completion() + self.model.generation_config.eos_token_id = [98, 99] + self.model.generate.return_value = torch.tensor([[1, 2, 3, 99, 99], [1, 2, 4, 5, 98]]) + self.tokenizer.decode.side_effect = ["result = 1" + END_CODE, "result = 2" + END_CODE] + assert completion(["short", "long"]) == [("result = 1", True), ("result = 2", True)] + assert [call.args[0] for call in self.tokenizer.decode.call_args_list] == [[3, 99], [4, 5, 98]] + assert self.tokenizer.padding_side == "left" @pytest.mark.parametrize("failure", [False, True]) diff --git a/model/benchmark/tests/test_trial.py b/model/benchmark/tests/test_trial.py index 0f4e939..f454a9e 100644 --- a/model/benchmark/tests/test_trial.py +++ b/model/benchmark/tests/test_trial.py @@ -1,5 +1,18 @@ +import json import pytest -from model.benchmark.src.trial import trial +from model.benchmark.src import trial, evaluate, inference +from model.benchmark.src.settings import Settings + + +def run(worker, record, generate, calls): + task = trial.trial(worker, record, calls) + prompt = next(task) + while True: + completion = generate(prompt) + try: + prompt = task.send(completion) + except StopIteration as result: + return result.value class Worker: @@ -23,6 +36,9 @@ def done(value): feedback.update(exception=f"{type(error).__name__}: {error}", done=None) return feedback + def close(self): + pass + @pytest.fixture def record(): @@ -46,7 +62,7 @@ def generate(prompt): prompts.append(prompt) return next(scripts), True - row = trial(worker, record, generate, 4) + row = run(worker, record, generate, 4) assert row["status"] == "passed" assert "ValueError: inspect values first" in prompts[1] for prompt in prompts: @@ -56,7 +72,7 @@ def generate(prompt): def test_done_does_not_bypass_checks(record): - row = trial(Worker(), record, lambda prompt: ("result = 999\ndone('ok')", True), 4) + row = run(Worker(), record, lambda prompt: ("result = 999\ndone('ok')", True), 4) assert row["status"] == "incorrect" assert "AssertionError" in row["error"] @@ -64,13 +80,13 @@ def test_done_does_not_bypass_checks(record): @pytest.mark.parametrize(("source", "ended"), [("result = 11", False), ("", True), (" \n", True)]) def test_invalid_completion_is_not_executed(record, source, ended): worker = Worker() - row = trial(worker, record, lambda prompt: (source, ended), 4) + row = run(worker, record, lambda prompt: (source, ended), 4) assert row["status"] == "boundary_error" assert len(worker.sources) == 1 def test_call_limit_is_enforced(record): - row = trial(Worker(), record, lambda prompt: ("result = 11", True), 2) + row = run(Worker(), record, lambda prompt: ("result = 11", True), 2) assert row["status"] == "call_limit" assert len(row["steps"]) == 2 @@ -78,7 +94,7 @@ def test_call_limit_is_enforced(record): def test_invalid_fixture_is_an_error(record): record["setup"] = "raise ValueError('bad fixture')" with pytest.raises(RuntimeError, match="Invalid fixture sum"): - trial(Worker(), record, lambda prompt: ("done('ok')", True), 4) + run(Worker(), record, lambda prompt: ("done('ok')", True), 4) def test_followup_preserves_workspace_and_has_its_own_budget(record): @@ -91,9 +107,44 @@ def generate(prompt): return next(scripts), True worker = Worker() - row = trial(worker, record, generate, 2) + row = run(worker, record, generate, 2) assert row["status"] == "passed" assert len(row["steps"]) == 4 assert sum(action == "reset" for _, action in worker.sources) == 1 assert prompts[2].endswith("<|task|>\nAdd one to the previous result.\n<|code|>\n") assert record["followup"]["check"] not in prompts[2] + + +@pytest.mark.parametrize("batch_size", [1, 2, 4]) +def test_batch_preserves_independent_workspaces_retries_and_followups(record, tmp_path, monkeypatch, batch_size): + records = [ + { + **record, + "id": str(index), + "setup": f"values = [{index}, 10]", + "check": f"assert result == {index + 10}", + "followup": {"instruction": "Add one.", "check": f"assert saved_result == {index + 10}\nassert result == {index + 11}"}, + } + for index in range(5) + ] + (tmp_path / "dev-tasks.jsonl").write_text("".join(json.dumps(row) + "\n" for row in records)) + + def generate(prompts): + completions = [] + for prompt in prompts: + if "Add one." in prompt: + source = "result = saved_result + 1\ndone('ok')" + elif "print(values)" in prompt: + source = "result = sum(values)\ndone('ok')" + else: + source = "print(values)" + completions.append((source, True)) + return completions + + monkeypatch.setattr(evaluate, "Worker", Worker) + monkeypatch.setattr(inference, "HFCompletion", lambda config: generate) + config = Settings(data=str(tmp_path), output=tmp_path / "results.jsonl", batch_size=batch_size) + evaluate.run(config) + rows = [json.loads(line) for line in config.output.read_text().splitlines()] + assert {row["id"] for row in rows} == {row["id"] for row in records} + assert all(row["status"] == "passed" and len(row["steps"]) == 3 for row in rows) diff --git a/model/cache.py b/model/cache.py new file mode 100644 index 0000000..4850cb2 --- /dev/null +++ b/model/cache.py @@ -0,0 +1,120 @@ +import argparse +import hashlib +import importlib.metadata +import json +import os +import platform +import re +import shutil +import subprocess +from pathlib import Path + +from model import ci +from model.benchmark.src.settings import Settings + + +def fingerprint(directory: Path) -> dict: + native = json.loads((directory / "baseline/adapter_config.json").read_text()) + if not re.fullmatch(r"[0-9a-f]{40}", native.get("revision") or ""): + raise ValueError("Baseline caching requires a pinned base model revision") + paths = ci.git( + "ls-files", + "model/benchmark", + "model/protocol", + "src", + "model/ci.py", + "model/cache.py", + ".github/workflows/model.yml", + ).splitlines() + files = { + path: hashlib.sha256(Path(path).read_bytes()).hexdigest() for path in paths + } + for path in sorted((directory / "baseline").glob("adapter_*")): + files[path.name] = hashlib.sha256(path.read_bytes()).hexdigest() + return { + "files": files, + "model": json.loads((directory / "baseline.json").read_text()), + "python": platform.python_version(), + "packages": sorted( + (package.metadata["Name"], package.version) + for package in importlib.metadata.distributions() + ), + "image": subprocess.check_output( + [ + "docker", + "image", + "inspect", + "pyshell-pyshell:latest", + "--format", + "{{.Id}}", + ], + text=True, + ).strip(), + "gpu": subprocess.check_output( + [ + "nvidia-smi", + "--query-gpu=name,driver_version,compute_cap", + "--format=csv,noheader", + ], + text=True, + ).strip(), + "environment": { + name: os.environ.get(name) + for name in ( + "CUDA_VISIBLE_DEVICES", + "CUBLAS_WORKSPACE_CONFIG", + "NVIDIA_TF32_OVERRIDE", + "OMP_NUM_THREADS", + "PYTHONHASHSEED", + ) + }, + } + + +def validate(path: Path) -> None: + ci.score(path) + rows = [json.loads(line) for line in path.read_text().splitlines()] + config = Settings() + tasks = [ + json.loads(line) + for line in (Path(config.data) / "dev-tasks.jsonl").read_text().splitlines() + ] + if {(row["id"], row["family"]) for row in rows} != { + (task["id"], task["family"]) for task in tasks + }: + raise ValueError("Cached baseline must contain the complete current benchmark") + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("action", choices=["key", "store", "restore"]) + parser.add_argument("--directory", type=Path, required=True) + args = parser.parse_args() + directory = args.directory + manifest = directory / "baseline-cache-key.json" + cache = Path(".baseline-cache") + if args.action == "key": + inputs = fingerprint(directory) + manifest.write_text(json.dumps(inputs, sort_keys=True)) + key = "baseline-v1-" + hashlib.sha256(manifest.read_bytes()).hexdigest() + with Path(os.environ["GITHUB_OUTPUT"]).open("a") as file: + file.write(f"key={key}\n") + elif args.action == "store": + validate(directory / "baseline.jsonl") + cache.mkdir() + shutil.copy2(manifest, cache / "manifest.json") + for name in ("baseline.jsonl", "baseline.jsonl.config.json"): + shutil.copy2(directory / name, cache / name) + else: + if (cache / "manifest.json").read_bytes() != manifest.read_bytes(): + raise ValueError("Cached baseline inputs do not match this run") + validate(cache / "baseline.jsonl") + for name in ("baseline.jsonl", "baseline.jsonl.config.json"): + target = directory / name + if target.exists(): + raise FileExistsError(target) + shutil.copy2(cache / name, target) + + +if __name__ == "__main__": + main() diff --git a/model/ci.py b/model/ci.py index de97183..b8c862d 100644 --- a/model/ci.py +++ b/model/ci.py @@ -101,6 +101,7 @@ def evaluate(directory: Path, adapter: str, output: str) -> None: { **settings.SETTINGS.model_dump(), "device": "cuda", + "batch_size": 4, "adapter": directory / adapter, "output": directory / output, } diff --git a/model/tests/test_cache.py b/model/tests/test_cache.py new file mode 100644 index 0000000..412003f --- /dev/null +++ b/model/tests/test_cache.py @@ -0,0 +1,176 @@ +import json +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from model import cache +from model.benchmark.src.settings import Settings + + +@pytest.fixture +def baseline(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + subprocess.run(["git", "init", "-q"], check=True) + for name in ( + "model/benchmark/data/dev-tasks.jsonl", + "model/benchmark/src/inference.py", + "model/protocol/src/pyshell/serialization.py", + "src/api/src/api/shell.py", + "model/ci.py", + "model/cache.py", + ".github/workflows/model.yml", + "model/train/data/train.jsonl", + ): + path = tmp_path / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("original") + subprocess.run(["git", "add", "."], check=True) + directory = tmp_path / "run" + (directory / "baseline").mkdir(parents=True) + (directory / "baseline/adapter_config.json").write_text( + json.dumps({"revision": "a" * 40}) + ) + (directory / "baseline/adapter_model.safetensors").write_bytes(b"weights") + (directory / "baseline.json").write_text( + json.dumps({"repo": "test/model", "revision": "b" * 40}) + ) + check_output = subprocess.check_output + + def command(args, **kwargs): + if args[0] == "docker": + return "sha256:image\n" + if args[0] == "nvidia-smi": + return "RTX 4090, driver, 8.9\n" + return check_output(args, **kwargs) + + monkeypatch.setattr(subprocess, "check_output", command) + return directory + + +@pytest.mark.parametrize( + "path", + [ + "model/benchmark/data/dev-tasks.jsonl", + "model/benchmark/src/inference.py", + "model/protocol/src/pyshell/serialization.py", + "src/api/src/api/shell.py", + "model/ci.py", + "model/cache.py", + ".github/workflows/model.yml", + "run/baseline/adapter_config.json", + "run/baseline/adapter_model.safetensors", + "run/baseline.json", + ], +) +def test_evaluation_inputs_invalidate_cache(baseline, path): + before = cache.fingerprint(baseline) + target = baseline.parent / path + if target.suffix == ".json": + target.write_text(json.dumps({"repo": "test/model", "revision": "c" * 40})) + else: + target.write_bytes(target.read_bytes() + b"changed") + assert cache.fingerprint(baseline) != before + + +def test_training_only_changes_keep_cache_key(baseline): + before = cache.fingerprint(baseline) + (baseline.parent / "model/train/data/train.jsonl").write_text("changed") + assert cache.fingerprint(baseline) == before + + +def test_runtime_changes_invalidate_cache(baseline, monkeypatch): + before = cache.fingerprint(baseline) + monkeypatch.setenv("NVIDIA_TF32_OVERRIDE", "1") + assert cache.fingerprint(baseline) != before + monkeypatch.delenv("NVIDIA_TF32_OVERRIDE") + monkeypatch.setattr( + cache.importlib.metadata, + "distributions", + lambda: [SimpleNamespace(metadata={"Name": "torch"}, version="different")], + ) + assert cache.fingerprint(baseline) != before + + +@pytest.mark.parametrize("executable", ["docker", "nvidia-smi"]) +def test_image_and_gpu_changes_invalidate_cache(baseline, monkeypatch, executable): + before = cache.fingerprint(baseline) + original = subprocess.check_output + + def command(args, **kwargs): + return "changed" if args[0] == executable else original(args, **kwargs) + + monkeypatch.setattr(subprocess, "check_output", command) + assert cache.fingerprint(baseline) != before + + +def test_key_is_stable_and_emitted_for_actions(baseline, monkeypatch): + output = baseline / "outputs" + monkeypatch.setenv("GITHUB_OUTPUT", str(output)) + monkeypatch.setattr(sys, "argv", ["cache", "key", "--directory", str(baseline)]) + cache.main() + cache.main() + first, second = output.read_text().splitlines() + assert first == second + assert first.startswith("key=baseline-v1-") + (baseline / "baseline/adapter_model.safetensors").write_bytes(b"new weights") + cache.main() + assert output.read_text().splitlines()[-1] != first + + +@pytest.mark.parametrize("revision", [None, "main"]) +def test_unpinned_base_model_cannot_be_cached(baseline, revision): + (baseline / "baseline/adapter_config.json").write_text( + json.dumps({"revision": revision}) + ) + with pytest.raises(ValueError, match="pinned"): + cache.fingerprint(baseline) + + +def test_cache_roundtrip_validates_inputs_tasks_and_preserves_provenance( + baseline, monkeypatch +): + config = Settings() + tasks = [ + json.loads(line) + for line in (Path(config.data) / "dev-tasks.jsonl").read_text().splitlines() + ] + rows = [ + {"id": task["id"], "family": task["family"], "status": "passed"} + for task in tasks + ] + output = baseline / "baseline.jsonl" + output.write_text("".join(json.dumps(row) + "\n" for row in rows)) + provenance = baseline / "baseline.jsonl.config.json" + provenance.write_text('{"commit":"original"}') + manifest = baseline / "baseline-cache-key.json" + manifest.write_text('{"inputs":"original"}') + + def run(action): + monkeypatch.setattr( + sys, "argv", ["cache", action, "--directory", str(baseline)] + ) + cache.main() + + run("store") + output.unlink() + provenance.unlink() + manifest.write_text('{"inputs":"changed"}') + with pytest.raises(ValueError, match="inputs do not match"): + run("restore") + assert not output.exists() + manifest.write_text('{"inputs":"original"}') + run("restore") + assert [json.loads(line) for line in output.read_text().splitlines()] == rows + assert json.loads(provenance.read_text()) == {"commit": "original"} + with pytest.raises(FileExistsError): + run("restore") + output.unlink() + (baseline.parent / ".baseline-cache/baseline.jsonl").write_text( + json.dumps(rows[0]) + "\n" + ) + with pytest.raises(ValueError, match="complete current benchmark"): + run("restore") + assert not output.exists()