Files
prime-rl/src/prime_rl/orchestrator/eval_sink.py
T
cb74ae2beb feat: bump verifiers to 0.2.2.dev7, adopt the multi-agent episode wire (#3104)
* feat: bump verifiers to 0.2.2.dev7, adopt the multi-agent episode wire

Companion to PrimeIntellect-ai/verifiers#1939 (multi-agent api). Re-pins
deps/verifiers to 192fd8ef0 (= 0.2.2.dev7) and deps/pydantic-config to
v0.4.2 (verifiers now requires prime-pydantic-config>=0.4.2).

- Serve wire: the env-server route run_rollout -> run, answering one
  Episode envelope ({id, env, ok, errors, traces}) per env-rollout.
  Env.run returns list[Rollout]; an episode that failed before minting
  any trace raises (the dispatcher synthesizes its error marker), and a
  not-ok episode marks its clean traces failed so a broken episode's
  partial seats are never trained on.
- The episode is the pipeline currency: the dispatcher emits one episode
  (list[Rollout]) per completed task onto out_q (a legacy run_group
  result emits its traces as single-trace episodes), and both sinks
  count episodes - never loose traces - toward group_size and eval epoch
  sizes. episode_id is stamped into info so saved records keep grouping.
- ok is the success sentinel: has_error now reads it, so the dispatcher's
  empty-trajectory promotion also flips ok, and error markers carry it.
- Only the trainable subset becomes training samples: a trace stamped
  untrainable (a multi-agent env's frozen agent) is never tokenized,
  never enters the group advantage, and never ships; it still lands in
  the trace files and observation window.
- Config shape: everything env lives under the env block, following the
  new vf.EnvServerConfig (env.taskset, env.agent.harness, per-agent caps
  under env.agent.*). All checked-in TOMLs migrated; the spawned env
  server receives the picklable env block via env_config_data.
- run_group survives only for v0/legacy bridge envs (a v1 server refuses
  it and always reports requires_group_scoring=False); vf's @group_reward
  removal doesn't touch prime-rl's own Algorithm.score_group.

Verified: tests/unit green (487 passed; config-loading params covered all
migrated TOMLs), ruff clean, and a 3-step reverse-text RL run on 2 GPUs
trains at 0% errors with every saved trace carrying ok, agent.name,
agent.trainable, and a distinct info.episode_id.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: trim narrative comments to the load-bearing facts

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: count buffered sink progress in episodes; explicit ok=False on cancel markers

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix: keep untrainable traces out of the effective views and the derived avg@k

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 16:44:20 -07:00

129 lines
5.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""EvalSink: three-level rollout sink for eval epochs.
Same shape as ``TrainSink``, but no tokenization / advantages / filters:
1. ``process_rollout`` — no-op.
2. ``process_group`` — at ``group_size`` episodes, move the rollouts
(errored ones included) into the ``(env, eval_step)`` bucket.
3. ``process_batch`` — at ``num_examples × group_size`` episodes, return an
``EvalBatch`` with the full returned cohort (metrics are computed downstream).
``add()`` takes one episode (``list[Rollout]``) and returns ``EvalBatch | None``;
all accounting counts episodes, never loose traces.
"""
from __future__ import annotations
import uuid
from collections import defaultdict
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.metrics import EvalRollouts
from prime_rl.orchestrator.types import EvalBatch, Rollout
from prime_rl.utils.logger import get_logger
class EvalSink:
"""Constructed only when eval is configured."""
def __init__(self, *, eval_envs: EvalEnvs) -> None:
self.eval_envs = eval_envs
self.pending_groups: dict[uuid.UUID, list[Rollout]] = defaultdict(list)
# Episodes arrived per group / per batch bucket — the finalization counts.
self.pending_group_episodes: dict[uuid.UUID, int] = defaultdict(int)
self.pending_batches: dict[tuple[str, int], list[Rollout]] = defaultdict(list)
self.pending_batch_episodes: dict[tuple[str, int], int] = defaultdict(int)
def add(self, episode: list[Rollout]) -> EvalBatch | None:
"""Process one episode arrival; finalize the group on the ``group_size``-th
episode and the per-env epoch on the ``num_examples × group_size``-th."""
env_name = episode[0].env_name
group_id = episode[0].group_id
for rollout in episode:
self.process_rollout(rollout)
bkey = (env_name, episode[0].eval_step)
self.pending_groups[group_id].extend(episode)
self.pending_group_episodes[group_id] += 1
if self.pending_group_episodes[group_id] >= self.group_size_for(env_name):
self.process_group(group_id)
if self.pending_batch_episodes[bkey] >= self.batch_size_for(env_name):
return self.process_batch(bkey)
return None
def group_size_for(self, env_name: str) -> int:
return self.eval_envs.get(env_name).config.group_size
def batch_size_for(self, env_name: str) -> int:
"""``num_examples × group_size`` — total episodes expected for one
epoch of ``env_name``."""
env = self.eval_envs.get(env_name)
return len(env.examples) * env.config.group_size
def batch_progress(self) -> list[tuple[str, int, int, int, int]]:
"""One entry per accumulating ``(env, eval_step)`` batch:
``(env_name, eval_step, batch_count, expected, buffered)``.
``batch_count`` is finalized-group episodes in ``pending_batches``;
``buffered`` is partial-group episode arrivals from non-group-scoring envs."""
batch_counts: dict[tuple[str, int], int] = dict(self.pending_batch_episodes)
buffered: dict[tuple[str, int], int] = {}
for group_id, rollouts in self.pending_groups.items():
if not rollouts:
continue
env_name = rollouts[0].env_name
if self.eval_envs.get(env_name).requires_group_scoring:
continue
bkey = (env_name, rollouts[0].eval_step)
buffered[bkey] = buffered.get(bkey, 0) + self.pending_group_episodes.get(group_id, 0)
return [
(
env_name,
eval_step,
batch_counts.get((env_name, eval_step), 0),
self.batch_size_for(env_name),
buffered.get((env_name, eval_step), 0),
)
for (env_name, eval_step) in set(batch_counts) | set(buffered)
]
# ── level 1: per-rollout (no-op for eval) ─────────────────────────────
def process_rollout(self, rollout: Rollout) -> None:
"""No-op. Eval rollouts don't need trainer-bound tokenization; the
method exists to keep the three-level structure uniform with
``TrainSink``.
"""
return None
# ── level 2: per-group (move into batch bucket) ───────────────────────
def process_group(self, group_id: uuid.UUID) -> None:
group = self.pending_groups.pop(group_id, [])
episodes = self.pending_group_episodes.pop(group_id, 0)
if not group:
return
env_name = group[0].env_name
task_idx = group[0].task.data.idx
eval_step = group[0].eval_step
bucket = self.pending_batches[(env_name, eval_step)]
bucket.extend(group)
self.pending_batch_episodes[(env_name, eval_step)] += episodes
survivors = [r for r in group if not r.has_error]
num_errored = len(group) - len(survivors)
rewards = [r.reward for r in survivors]
avg_reward = sum(rewards) / len(rewards) if rewards else 0.0
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} eval_step={eval_step} | "
f"rollouts={len(group)} (errored={num_errored}) | reward={avg_reward:.4f}"
)
def process_batch(self, key: tuple[str, int]) -> EvalBatch:
"""Pop the finished ``(env, eval_step)`` epoch and return the ``EvalBatch`` with its full
returned cohort (errored rollouts included — the ``all`` set). Metrics are computed
downstream via ``EvalBatch.rollouts.metrics`` over the all/effective subsets, so the sink
does no aggregation."""
env_name, step = key
rollouts = self.pending_batches.pop(key, [])
self.pending_batch_episodes.pop(key, None)
return EvalBatch(env_name=env_name, step=step, rollouts=EvalRollouts(rollouts))