-
Notifications
You must be signed in to change notification settings - Fork 459
Implement monitor rubrics #653
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
base: main
Are you sure you want to change the base?
Changes from all commits
4bda90d
dfa1bc0
fb5b97f
7128ba2
ccdb539
42cba23
58ba11b
1d34438
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,6 +4,7 @@ | |
| from openai import AsyncOpenAI | ||
|
|
||
| import verifiers as vf | ||
| from verifiers.rubrics.monitor_rubric import MonitorRubric | ||
| from verifiers.types import ( | ||
| Messages, | ||
| ModelResponse, | ||
|
|
@@ -22,10 +23,16 @@ | |
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class MultiTurnMonitorRubric(MonitorRubric): | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. small nit -- what's the need for a distinct MultiTurnMonitorRubric class? All env classes currently extend MultiTurnEnv already, and build up the trajectory (even if single-turn)
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Risks other extensions (e.g. SandboxMonitorRubric) not being multi-turn compatible by default, which seems undesirable. |
||
| def __init__(self): | ||
| super().__init__(state_keys=[("trajectory", "num_turns", len)]) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this feels a bit restrictive/unintuitive + not totally seeing the value of the state_keys approach. we can already do: which is fairly concise + avoids the need for a new pattern could also be worth adding |
||
|
|
||
|
|
||
| class MultiTurnEnv(vf.Environment): | ||
| def __init__(self, max_turns: int = -1, **kwargs): | ||
| super().__init__(**kwargs) | ||
| self.max_turns = max_turns | ||
| self.add_rubric(MultiTurnMonitorRubric()) | ||
|
|
||
| async def setup_state(self, state: State) -> State: | ||
| return state | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -89,6 +89,22 @@ def teardown(self, wait: bool = True) -> None: | |
|
|
||
| class SandboxState(TypedDict): | ||
| ready: bool | ||
| ready_wait_time: float | ||
| command_execution_times: list[float] | ||
|
|
||
|
|
||
| class SandboxMonitorRubric(vf.MonitorRubric): | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is this serving a different role than MultiTurnMonitorRubric? is the idea to have many monitor rubrics which track new things introduced at different hierarchies? |
||
| def __init__(self): | ||
| super().__init__( | ||
| state_keys=[ | ||
| ("sandbox_state.ready_wait_time", "sandbox_ready_wait_time"), | ||
| ( | ||
| "sandbox_state.command_execution_times", | ||
| "sandbox_command_execution_time", | ||
| lambda x: sum(x) / len(x) if len(x) > 0 else 0.0, | ||
| ), | ||
| ] | ||
| ) | ||
|
|
||
|
|
||
| class SandboxCreationError(vf.SandboxError): ... | ||
|
|
@@ -127,6 +143,7 @@ def __init__( | |
| stop_errors=stop_errors if stop_errors is not None else [vf.SandboxError], | ||
| **kwargs, | ||
| ) | ||
| self.add_rubric(SandboxMonitorRubric()) | ||
| self.timeout_per_command_seconds = timeout_per_command_seconds | ||
| self.sandbox_client = ThreadedAsyncSandboxClient( | ||
| max_workers=sandbox_client_max_workers, | ||
|
|
@@ -173,7 +190,9 @@ async def _wait_for_sandbox_ready( | |
| sandbox_state["ready"] = True | ||
| except Exception as e: | ||
| raise SandboxNotReadyError(e) | ||
| self.logger.debug(f"Waited {time.time() - s:.1f}s for sandbox to be ready") | ||
| ready_wait_time = time.time() - s | ||
| sandbox_state["ready_wait_time"] = ready_wait_time | ||
| self.logger.debug(f"Waited {ready_wait_time:.1f}s for sandbox to be ready") | ||
|
|
||
| async def bash( | ||
| self, | ||
|
|
@@ -197,13 +216,16 @@ async def bash( | |
| timeout=self.timeout_per_command_seconds, | ||
| ) | ||
| except CommandTimeoutError: | ||
| e = time.time() | ||
| timeout_msg = f"Command timed out after {self.timeout_per_command_seconds}s" | ||
| self.logger.warning(f"{timeout_msg} in sandbox {sandbox_id}") | ||
| sandbox_state["command_execution_times"].append( | ||
| self.timeout_per_command_seconds | ||
| ) | ||
| return f"Error: {timeout_msg}" | ||
| except Exception as e: | ||
| raise vf.SandboxError from e | ||
| e = time.time() | ||
| command_execution_time = time.time() - s | ||
| sandbox_state["command_execution_times"].append(command_execution_time) | ||
| stdout = results.stdout.strip() | ||
| stderr = (results.stderr or "").strip() | ||
| combined = stdout | ||
|
|
@@ -213,7 +235,9 @@ async def bash( | |
| else: | ||
| combined = f"stderr:\n{stderr}" | ||
| output = combined or "(no output)" | ||
| self.logger.debug(f"Executed command in {e - s:.1f}s. Got output: {output}") | ||
| self.logger.debug( | ||
| f"Executed command in {command_execution_time:.1f}s. Got output: {output}" | ||
| ) | ||
| return output | ||
|
|
||
| async def post_rollout(self, state: vf.State): | ||
|
|
@@ -252,7 +276,11 @@ async def setup_state(self, state: vf.State, **kwargs) -> vf.State: | |
| self.active_sandboxes.add(sandbox.id) | ||
| self.logger.debug(f"Created sandbox {sandbox.id}") | ||
| state["sandbox_id"] = sandbox.id | ||
| state["sandbox_state"] = {"ready": False} | ||
| state["sandbox_state"] = { | ||
| "ready": False, | ||
| "ready_wait_time": None, | ||
| "command_execution_times": [], | ||
| } | ||
| return await super().setup_state(state, **kwargs) | ||
|
|
||
| def update_tool_args( | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| from typing import Callable | ||
|
|
||
| from verifiers.rubrics.rubric import Rubric | ||
| from verifiers.types import State | ||
|
|
||
| StateKey = str | ||
| RenamedStateKey = tuple[StateKey, str] | ||
| RenamedTransformedStateKey = tuple[StateKey, str, Callable[..., float]] | ||
|
|
||
|
|
||
| class MonitorRubric(Rubric): | ||
| """Simple rubric that reads values from the state for logging.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| state_keys: list[StateKey | RenamedStateKey | RenamedTransformedStateKey] | ||
| | None = None, | ||
| ): | ||
| self.state_keys: list[ | ||
| StateKey | RenamedStateKey | RenamedTransformedStateKey | ||
| ] = state_keys or [] | ||
|
|
||
| reward_funcs = [] | ||
| for state_key in self.state_keys: | ||
| if isinstance(state_key, str): | ||
| reward_func = self.get_read_from_state(state_key) | ||
| else: | ||
| reward_func = self.get_read_from_state(*state_key) # type: ignore | ||
| reward_funcs.append(reward_func) | ||
| reward_weights = [0.0] * len(self.state_keys) # only for logging | ||
|
|
||
| # pass them to parent class | ||
| super().__init__(funcs=reward_funcs, weights=reward_weights) | ||
|
|
||
| def get_read_from_state( | ||
| self, | ||
| key: str, | ||
| name: str | None = None, | ||
| transform: Callable[..., float] = float, | ||
| ) -> Callable: | ||
| """Create a reward function that reads from the state.""" | ||
|
|
||
| async def read_from_state(state: State) -> float: | ||
| key_parts = key.split(".") | ||
| for key_part in key_parts[:-1]: | ||
| state = state.get(key_part, {}) | ||
| value = state.get(key_parts[-1], 0.0) | ||
| return transform(value) | ||
|
|
||
| read_from_state.__name__ = name if name is not None else key | ||
|
|
||
| return read_from_state |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
if self.rubric is already a RubricGroup, maybe we should do self.rubric.add_rubric ?