Repository navigation
feat: add vf-run, a minimal in-process runner #3047
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| """`vf-run` resolves a typed config from the CLI without a model.""" | ||
|
|
||
| import asyncio | ||
| import contextlib | ||
| import json | ||
|
|
||
| import pytest | ||
|
|
||
| from verifiers.v1.cli import run | ||
| from verifiers.v1.cli.output import CONFIG_DIR, RESOLVED_DIR | ||
| from verifiers.v1.cli.run import USAGE, main | ||
| from verifiers.v1.configs.cli.run import RunnerConfig | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def keep_stdlib_logging(monkeypatch): | ||
| """`main` routes logging through loguru for the whole process; keep other tests' | ||
| `caplog` working.""" | ||
| monkeypatch.setattr(run, "setup_logging", lambda *args, **kwargs: None) | ||
|
|
||
|
|
||
| def test_dry_run_writes_config(tmp_path): | ||
| main( | ||
| [ | ||
| "reverse-text", | ||
| "-n", | ||
| "2", | ||
| "-r", | ||
| "3", | ||
| "-o", | ||
| str(tmp_path), | ||
| "--run.dir", | ||
| "run", | ||
| "--dry-run", | ||
| ] | ||
| ) | ||
| run_dir = tmp_path / "run" | ||
| config = json.loads((run_dir / CONFIG_DIR / RESOLVED_DIR / "run.json").read_text()) | ||
| assert config["env"]["taskset"]["id"] == "reverse-text" | ||
| assert config["select"]["limit"] == 2 | ||
| assert config["num_rollouts"] == 3 | ||
| assert not (run_dir / "traces.jsonl").exists() | ||
|
|
||
|
|
||
| def test_refuses_a_run_dir_with_results(tmp_path): | ||
| run_dir = tmp_path / "run" | ||
| run_dir.mkdir() | ||
| (run_dir / "traces.jsonl").write_text("{}\n") | ||
| with pytest.raises(SystemExit, match="already contains results"): | ||
| main(["reverse-text", "-o", str(tmp_path), "--run.dir", "run", "--dry-run"]) | ||
|
|
||
|
|
||
| def test_needs_a_taskset(): | ||
| with pytest.raises(SystemExit, match="usage") as exc: | ||
| main(["-n", "1"]) | ||
| assert str(exc.value) == USAGE | ||
|
|
||
|
|
||
| async def test_failed_rollout_cancels_siblings_before_teardown(tmp_path, monkeypatch): | ||
| events: list[str] = [] | ||
|
|
||
| class Taskset(list): | ||
| bounded = True | ||
|
|
||
| def select(self, _select): | ||
| return self | ||
|
|
||
| class FakeEnv: | ||
| taskset = Taskset(["fail", "slow"]) | ||
|
|
||
| def slots(self, task, n): | ||
| return [task] * n | ||
|
|
||
| async def run_slot(self, slot, ctx, semaphore, on_complete): | ||
| if slot == "fail": | ||
| await asyncio.sleep(0) | ||
| raise RuntimeError("boom") | ||
| try: | ||
| await asyncio.sleep(60) | ||
| finally: | ||
| events.append("sibling unwound") | ||
|
|
||
| @contextlib.asynccontextmanager | ||
| async def serving(self): | ||
| try: | ||
| yield | ||
| finally: | ||
| events.append("teardown") | ||
|
|
||
| monkeypatch.setattr(run, "load_environment", lambda env: FakeEnv()) | ||
| config = RunnerConfig(env={"taskset": {"id": "reverse-text"}}, output_dir=tmp_path) | ||
| with pytest.raises(RuntimeError, match="boom"): | ||
| await run.run_episodes(config) | ||
| assert events == ["sibling unwound", "teardown"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| """The `vf-run` entrypoint: run a taskset's episodes in-process and save their traces. | ||
|
|
||
| Prints one summary line and exits non-zero when any episode is not ok, so CI can call | ||
| it directly. For full evaluations, use prime-rl's `uv run eval`. | ||
| """ | ||
|
|
||
| import asyncio | ||
| import logging | ||
| import os | ||
| import sys | ||
|
|
||
| from pydantic_config import cli | ||
|
|
||
| from verifiers.v1.cli.output import output_path, save_config, write_config | ||
| from verifiers.v1.cli.resolve import ( | ||
| extract_id, | ||
| narrow_config, | ||
| plugin_errors, | ||
| references_config_file, | ||
| with_positional_taskset, | ||
| ) | ||
| from verifiers.v1.clients import ModelContext | ||
| from verifiers.v1.configs.cli.run import RunnerConfig | ||
| from verifiers.v1.episode import Episode | ||
| from verifiers.v1.trace import EvalRunInfo | ||
| from verifiers.v1.utils.interrupt import install_interrupt | ||
| from verifiers.v1.utils.loaders import load_environment | ||
| from verifiers.v1.utils.logging import setup_logging | ||
| from verifiers.v1.utils.trace_store import TRACES_FILE, append_episode | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| USAGE = "usage: uv run vf-run [<taskset-id>] [--env.id <id>] [-m <model>] [-n <tasks>] [-r <rollouts>] [options] [@ file.toml]" | ||
|
|
||
|
|
||
| async def run_episodes(config: RunnerConfig) -> list[Episode]: | ||
| """Run `num_rollouts` episodes per selected task and append each to `traces.jsonl` | ||
| as it completes.""" | ||
| env = load_environment(config.env) | ||
| taskset = env.taskset.select(config.select) | ||
| if not taskset.bounded: | ||
| raise ValueError( | ||
| f"{type(taskset).__name__} is infinite - bound the run with -n" | ||
| ) | ||
| out = output_path(config) | ||
| save_config(config, out, "run.json") | ||
| ctx = ModelContext( | ||
| client=config.client, model=config.model, sampling=config.sampling | ||
| ) | ||
| semaphore = ( | ||
| asyncio.Semaphore(config.max_concurrent) if config.max_concurrent else None | ||
| ) | ||
| write_lock = asyncio.Lock() | ||
|
|
||
| async def on_complete(episode: Episode) -> None: | ||
| episode.record_run(EvalRunInfo(id=config.run.id, name=config.run.name)) | ||
| await append_episode(out, episode, write_lock) | ||
|
|
||
| async with env.serving(): | ||
| rollouts = [ | ||
| asyncio.ensure_future(env.run_slot(slot, ctx, semaphore, on_complete)) | ||
| for task in taskset | ||
| for slot in env.slots(task, config.num_rollouts) | ||
| ] | ||
| try: | ||
| return list(await asyncio.gather(*rollouts)) | ||
|
macroscopeapp[bot] marked this conversation as resolved.
Resolved
|
||
| except BaseException: | ||
| # Unwind every sibling before `serving()` tears down the resources they use. | ||
| for rollout in rollouts: | ||
| rollout.cancel() | ||
| await asyncio.gather(*rollouts, return_exceptions=True) | ||
| raise | ||
|
|
||
|
|
||
| def main(argv: list[str] | None = None) -> None: | ||
| argv = with_positional_taskset(list(sys.argv[1:]) if argv is None else list(argv)) | ||
| if not argv or any(arg in ("-h", "--help") for arg in argv): | ||
| print(USAGE) | ||
| sys.argv = [sys.argv[0], "--help"] | ||
| with plugin_errors(): | ||
| cli(narrow_config(RunnerConfig, argv)) | ||
| return | ||
| if ( | ||
| not extract_id(argv, "env.taskset") | ||
| and not references_config_file(argv) | ||
| and not any(a.startswith("--env.") for a in argv) | ||
| ): | ||
| raise SystemExit(USAGE) | ||
|
|
||
| with plugin_errors(): | ||
| config_type = narrow_config(RunnerConfig, argv) | ||
| sys.argv = [sys.argv[0], *argv] | ||
| config = cli(config_type) | ||
| setup_logging("DEBUG" if config.verbose else "INFO") | ||
| out = output_path(config) | ||
| traces_file = out / TRACES_FILE | ||
| if traces_file.exists() and traces_file.stat().st_size > 0: | ||
| raise SystemExit(f"{out} already contains results - pick another --run.dir") | ||
| if config.dry_run: | ||
| logger.info("wrote config to %s", write_config(config, out, "run.json")) | ||
| return | ||
|
|
||
| # The run identity: every process this run spawns inherits it. | ||
| os.environ.setdefault("VF_RUN_ID", config.run.id) | ||
| # A first Ctrl-C raises KeyboardInterrupt so each rollout's teardown still runs. | ||
| install_interrupt() | ||
| try: | ||
| episodes = asyncio.run(run_episodes(config)) | ||
| except KeyboardInterrupt: | ||
| raise SystemExit(130) | ||
| traces = [trace for episode in episodes for trace in episode.traces] | ||
| ok = sum(episode.ok for episode in episodes) | ||
| reward = sum(trace.reward for trace in traces) / len(traces) if traces else 0.0 | ||
| print(f"{ok}/{len(episodes)} episodes ok, mean reward {reward:.3f}: {out}") | ||
| if ok < len(episodes): | ||
| raise SystemExit(1) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.