Compare commits

..
Author SHA1 Message Date
Mika SenghaasandGitHub d09bf96dbe feat: cancel superseded online eval episodes (#3402)
## Summary
- cancel queued and in-flight SFT eval episodes when the trainer offers
a newer checkpoint
- report scores from completed episodes and log the cancelled count and
fraction for each superseded checkpoint
- show the cancellation fraction in the local dashboard and W&B eval
sections
- allow `eval.cancel_on_new_checkpoint = false` to drain every epoch,
which can idle the trainer while slow evals finish
- document the online-eval behavior and configuration

## Verification
- `uv run ruff check
packages/prime-rl-configs/src/prime_rl/configs/evals.py
src/prime_rl/evals/evals.py src/prime_rl/monitors/wandb/overview.py
tests/unit/test_configs.py`
- `node --check src/prime_rl/dashboard/static/app.js`
- `uv run pytest tests/unit/test_configs.py -q` (122 passed)
- two-GPU SFT and online-eval run with NCCL broadcast (steps 0 and 1
reported partial scores with 6 of 8 episodes cancelled; step 2 completed
all 8 episodes; the launcher exited successfully)
- dashboard browser smoke test for the cancellation panel and run
metrics
- `PYTEST_OUTPUT_DIR=/tmp/prime-rl-eval-cancel-tests uv run pytest
tests/unit -m "not gpu" -q` (477 passed, 86 deselected; one unrelated
baseline Qwen3-VL fixture failure in
`tests/unit/orchestrator/test_qwen3_vl_e2e.py`)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes online eval scheduling and trainer–evals checkpoint handoff;
mis-cancellation could skew eval metrics or stall weight updates, but
behavior is configurable and scoped to online evals.
> 
> **Overview**
> Online SFT evals now **preempt unfinished epochs** when the trainer
publishes a newer checkpoint, so slow eval rollouts no longer block
loading the next weights. This is the default
(`eval.cancel_on_new_checkpoint = true`); set it to `false` to finish
every triggered epoch (the trainer may idle waiting).
> 
> The evals loop detects a superseding published step, calls
**`Dispatcher.cancel_eval_step`**, and **`EvalSink`** counts cancelled
groups toward partial epochs instead of treating `GroupCancellation` as
fatal. **`GroupCancellation`** carries the eval **`step`** and a
**`superseded`** reason. Weight reload hooks **`on_version_pending` /
`on_new_version`** run before consuming the epoch. Partial results still
log with **`eval/{env}/all/cancelled/count`** and **`cancelled/mean`**
(dashboard and W&B overview panels added).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
730dce804cc20fb3257c8c3a457bb22f95a82e94. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-08-26 11:32:01 -07:00
10 changed files with 182 additions and 30 deletions
+1 -1
View File
@@ -198,7 +198,7 @@ num_train_gpus = 1 # trainer
num_infer_gpus = 1 # inference
```
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the evals process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
The launcher starts the inference server, one env server per eval source, and an `evals` process next to the trainer. NCCL is the default weight transport. The trainer broadcasts weights at startup (fail-fast) and at every step an eval env is due, Every broadcast runs the same four-stage handshake in `broadcasts/step_{n}`: the trainer offers the version (`.sender_ready`) and blocks, the evals process acknowledges (`.receiver_ready`), then the trainer transfers (`.started`) and commits (`.finished`). It runs the due envs sequentially per broadcast, so every epoch measures exactly one policy version. Set `[weight_broadcast] type = "filesystem"` to reload weights from disk instead. LoRA and externally managed inference use filesystem broadcast automatically. The base model is evaluated before the first step (disable with `eval.skip_first_step`), and the final broadcast always fires every env. In-flight eval episodes are cancelled by default when the next checkpoint is ready, so stale evals do not delay a weight update. Set `eval.cancel_on_new_checkpoint = false` to drain every triggered epoch instead. The trainer can idle while it waits for slow evals. They are sized by the same adaptive concurrency controller as the orchestrator; bound it with `[eval.concurrency]` (`min_inflight` / `max_inflight`; set them equal for fixed concurrency).
#### Multi-Node Trainer and Inference Pool
@@ -27,6 +27,11 @@ class EvalsEvalConfig(EvalConfig):
"""Adaptive in-flight episode concurrency (``[eval.concurrency]``), sized by the
same controller as the orchestrator's ``[orchestrator.concurrency]``."""
cancel_on_new_checkpoint: bool = True
"""For online evals, cancel unfinished episodes when a newer trainer checkpoint is ready.
Disable to finish every triggered eval epoch before loading later weights. The trainer can
idle while it waits for slow evals."""
@property
def env_addresses(self) -> dict[tuple[str, str], str]:
"""Where each eval source's env server lives, keyed by ``("eval", resolved_name)``.
+1 -1
View File
@@ -96,7 +96,7 @@ curl http://localhost:8000/v1/chat/completions \
## `evals` — multi-env evals
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. With `[online]` (`broadcasts_dir`, `max_steps`, `resume_step`): watch the broadcasts dir for stable `step_{n}` weight broadcasts and evaluate each — the `sft` launcher writes this config for online evals. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
Runs the configured eval sources against a live inference server. Standalone (no `[online]` block): one epoch of every source against the served weights, then exit. With `[online]` (`broadcasts_dir`, `max_steps`, `resume_step`): watch the broadcasts dir for stable `step_{n}` weight broadcasts and evaluate each — the `sft` launcher writes this config for online evals. By default a newer checkpoint cancels unfinished episodes from the prior eval. Set `eval.cancel_on_new_checkpoint = false` to drain every epoch. The trainer can idle while it waits for slow evals. Launcher-managed SFT evals use NCCL weight broadcast by default, including multi-node SLURM deployments. LoRA and external inference use filesystem broadcast.
```bash
uv run inference --vllm.model Qwen/Qwen3-4B # start inference separately
+1
View File
@@ -576,6 +576,7 @@ function buildSections(meta) {
{ regex: `eval/${envPattern}/effective/[^/]+/avg@.*` },
{ regex: `eval/${envPattern}/effective/[^/]+/reward/mean`, split: true },
{ regex: `eval/${envPattern}/all/[^/]+/reward/mean`, split: true },
{ regex: `eval/${envPattern}/all/cancelled/mean` },
...COMMON_METRICS.map((m) => ({ regex: `eval/${envPattern}/${m}` })),
...COMMON_REGEXES.map((r) => ({ regex: `eval/${envPattern}/${r}` })),
],
+75 -15
View File
@@ -13,8 +13,9 @@ inside the handshake until the receiver acknowledges.
Scheduling reuses the orchestrator pipeline unchanged: an eval-only
``Dispatcher`` admits episodes under the adaptive ``ConcurrencyController``,
fed by the ``InferenceMetricsCollector``'s ``/metrics`` polls. Eval episodes
are version-pinned measurements, so an overload cut only blocks admission and
the in-flight pool drains through natural completions.
are version-pinned measurements. By default, a newer online checkpoint cancels
unfinished episodes from the prior version; callers can disable this when they need
every epoch to drain.
Env servers: sources without an explicit ``serve.address`` get an env server
spawned by the evals process at their derived address; sources with one are
@@ -322,6 +323,20 @@ class Evals:
break
await asyncio.sleep(POLL_INTERVAL_S)
def next_published_step(self, step: int) -> int | None:
"""Return the first newer checkpoint offered by the trainer."""
assert self.config.online is not None
assert self.config.online.broadcasts_dir is not None
assert self.receiver is not None
return next(
(
candidate
for candidate in get_all_ckpt_steps(self.config.online.broadcasts_dir)
if candidate > step and self.receiver.is_published(candidate)
),
None,
)
def deleted_due_steps(self, steps: list[int], newest_published: int | None) -> set[int]:
"""Eval-due steps up to the newest published broadcast that are missing from
the broadcasts dir — the trainer wrote them (it broadcasts at every due step),
@@ -356,7 +371,10 @@ class Evals:
# Every offered version must be received: the trainer blocks inside
# the handshake, so a failed receive fails the run loudly.
get_logger().info(f"Updating inference weights to broadcast step {step} ({broadcast_dir})")
await self.dispatcher.on_version_pending(step)
await self.receiver.receive(step)
self.policy.version = step
await self.dispatcher.on_new_version(step)
if not fired:
return
@@ -371,34 +389,66 @@ class Evals:
# The dispatcher only schedules eval in PREFER_EVAL, so nothing dispatches
# between the trigger above and the weight reload completing.
self.policy.version = step
if not reload_weights:
self.policy.version = step
get_logger().info(f"Starting evals in {', '.join(fired)} at step {step} ({total_rollouts} total rollouts)")
self.dispatcher.switch_mode(DispatcherMode.PREFER_EVAL, reason=f"eval was triggered at step {step}")
await self.consume_epoch(fired)
await self.consume_epoch(fired, step)
async def consume_epoch(self, fired: list[str]) -> None:
"""Consume dispatcher episodes until every fired env's epoch finalizes,
routing them through the sink and monitors."""
# An env with no examples emits no episodes, so its epoch can never finalize.
async def consume_epoch(self, fired: list[str], step: int) -> None:
"""Consume one epoch, preempting it when a newer checkpoint is ready."""
pending = {env_name for env_name in fired if self.eval_sink.batch_size_for(env_name) > 0}
cancellation_task: asyncio.Task[int] | None = None
superseding_step: int | None = None
online = self.config.online
while pending:
item = await self.dispatcher.out_q.get()
if (
cancellation_task is None
and online is not None
and self.config.eval.cancel_on_new_checkpoint
and (superseding_step := self.next_published_step(step)) is not None
):
get_logger().warning(
f"Checkpoint {superseding_step} is ready - cancelling unfinished eval episodes for step {step}"
)
cancellation_task = asyncio.create_task(
self.dispatcher.cancel_eval_step(step), name=f"cancel-eval-step-{step}"
)
try:
if online is not None and self.config.eval.cancel_on_new_checkpoint:
item = await asyncio.wait_for(self.dispatcher.out_q.get(), timeout=POLL_INTERVAL_S)
else:
item = await self.dispatcher.out_q.get()
except asyncio.TimeoutError:
if cancellation_task is not None and cancellation_task.done():
cancellation_task.result()
continue
if isinstance(item, GroupCancellation):
raise RuntimeError("Eval dispatcher emitted a group cancellation")
if isinstance(item, DispatchFailure):
eval_batch = self.eval_sink.cancel(item)
elif isinstance(item, DispatchFailure):
eval_batch = self.eval_sink.fail(item)
else:
step = eval_work(item).step
await monitors.log([item], step, "eval", "all")
item_step = eval_work(item).step
await monitors.log([item], item_step, "eval", "all")
eval_batch = self.eval_sink.add(item)
if eval_batch is not None:
await self.finalize_eval_batch(eval_batch)
pending.discard(eval_batch.env_name)
if cancellation_task is not None:
cancelled = await cancellation_task
get_logger().warning(
f"Cancelled {cancelled} unfinished eval episodes for step {step}; "
f"advancing to checkpoint {superseding_step}"
)
async def finalize_eval_batch(self, batch: EvalBatch) -> None:
"""Persist + log one completed eval epoch through the monitors, mirroring the
orchestrator: effective episodes plus the ``eval/{env}/...`` metric dict."""
if not batch.episodes and not batch.failures:
if not batch.episodes and not batch.failures and not batch.cancelled:
get_logger().warning(f"Eval @ step={batch.step} env={batch.env_name}: no attempts returned, skipping log")
return
@@ -410,12 +460,15 @@ class Evals:
metrics: dict[str, float] = {}
for subset, pool in (("all", episodes), ("effective", effective)):
metrics |= pool.metrics.to_wandb(prefix=f"eval/{batch.env_name}", subset=subset)
total_attempts = len(episodes) + len(batch.failures)
total_attempts = len(episodes) + len(batch.failures) + batch.cancelled
metrics |= dispatch_failure_metrics(
batch.failures,
prefix=f"eval/{batch.env_name}/all",
total_attempts=total_attempts,
)
if batch.cancelled:
metrics[f"eval/{batch.env_name}/all/cancelled/count"] = float(batch.cancelled)
metrics[f"eval/{batch.env_name}/all/cancelled/mean"] = batch.cancelled / total_attempts
metrics[f"eval/{batch.env_name}/policy_version"] = float(batch.step)
metrics["step"] = float(batch.step)
await monitors.log(metrics, step=batch.step)
@@ -423,6 +476,13 @@ class Evals:
eff, full = effective.metrics, episodes.metrics
triggered_at = self.eval_triggered_at.pop((batch.env_name, batch.step), None)
elapsed = (time.perf_counter() - triggered_at) if triggered_at is not None else 0.0
if batch.cancelled:
get_logger().warning(
f"Partially evaluated {batch.env_name} (Step {batch.step}) | "
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
f"Completed {len(episodes)}/{total_attempts} | Cancelled {batch.cancelled}/{total_attempts}"
)
return
get_logger().success(
f"Evaluated {batch.env_name} (Step {batch.step}) | "
f"{format_time(elapsed):>7} | Reward {eff.reward.mean():.4f} | "
+1
View File
@@ -143,6 +143,7 @@ def eval_section(name: str, env_pattern: str) -> ws.Section:
return section(
name,
regexes=[f"eval/{env_pattern}/all/[^/]+/avg@.*", f"eval/{env_pattern}/effective/[^/]+/avg@.*"]
+ [f"eval/{env_pattern}/all/cancelled/mean"]
+ [f"eval/{env_pattern}/{m}" for m in COMMON_METRICS]
+ [f"eval/{env_pattern}/{r}" for r in COMMON_REGEXES],
)
+36 -1
View File
@@ -18,7 +18,7 @@
the weight update) drops train groups already past ``max_off_policy_steps`` — a
compute-saving early cancel; the sink's queue sweep is what guarantees the
bound. Eval episodes are measurements for the policy version they started
with, so they are allowed to finish even if training advances. Train
with. Online evals may explicitly cancel them when a newer checkpoint is ready. Train
episodes sampled from a frozen model never go stale — their generation
source doesn't change with policy updates.
"""
@@ -702,6 +702,7 @@ class Dispatcher:
kind=kind,
env_name=env_name,
group_id=str(group_id),
step=group.step if group is not None else claimed[-1][1].step,
count=cancelled,
reason=reason,
)
@@ -745,6 +746,40 @@ class Dispatcher:
await safe_cancel_all(train_tasks)
return cancelled
async def cancel_eval_step(self, step: int) -> int:
"""Cancel queued and active eval groups for a superseded checkpoint.
Scheduling remains paused until ``on_new_version`` runs after the
replacement weights are live.
"""
if self.eval_source is None or self.eval_envs is None:
return 0
self.policy_update_pending = True
async with self.scheduling_lock:
queued = self.eval_source.cancel_step(step)
group_ids = [gid for gid, group in self.groups.items() if group.kind == "eval" and group.step == step]
cancelled = 0
for group_id in group_ids:
cancelled += await self.drop_group(group_id, reason="superseded")
for request in queued:
count = self.eval_envs.get(request.env_name).config.group_size
cancelled += count
self.metrics.record_cancellation(kind="eval", env_name=request.env_name, n=count)
await self.out_q.put(
GroupCancellation(
kind="eval",
env_name=request.env_name,
group_id=str(uuid.uuid4()),
step=request.step,
count=count,
reason="superseded",
)
)
return cancelled
# ── metrics ────────────────────────────────────────────────────────────
def gauges(self) -> dict[str, float]:
+52 -10
View File
@@ -8,7 +8,7 @@ import verifiers.v1 as vf
from prime_rl.orchestrator.envs import EvalEnvs
from prime_rl.orchestrator.metrics import EvalEpisodes
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch
from prime_rl.orchestrator.types import DispatchFailure, EvalBatch, GroupCancellation
from prime_rl.orchestrator.utils import episode_env_name, episode_group_id, eval_work
from prime_rl.utils.logger import get_logger
@@ -20,8 +20,10 @@ class EvalSink:
self.eval_envs = eval_envs
self.pending_groups: dict[str, list[vf.Episode]] = defaultdict(list)
self.pending_group_failures: dict[str, list[DispatchFailure]] = defaultdict(list)
self.pending_group_cancellations: dict[str, GroupCancellation] = {}
self.pending_batches: dict[tuple[str, int], list[vf.Episode]] = defaultdict(list)
self.pending_batch_failures: dict[tuple[str, int], list[DispatchFailure]] = defaultdict(list)
self.pending_batch_cancellations: dict[tuple[str, int], int] = defaultdict(int)
def add(self, episode: vf.Episode) -> EvalBatch | None:
env_name = episode_env_name(episode)
@@ -50,11 +52,33 @@ class EvalSink:
return self.process_batch(bkey)
return None
def cancel(self, cancellation: GroupCancellation) -> EvalBatch | None:
"""Count a dispatcher-cancelled group toward its superseded eval epoch."""
if cancellation.kind != "eval":
raise ValueError(f"EvalSink cannot process a {cancellation.kind} group cancellation")
group_id = cancellation.group_id
bkey = (cancellation.env_name, cancellation.step)
self.pending_group_cancellations[group_id] = cancellation
if self._group_size(group_id) >= self.group_size_for(cancellation.env_name):
self.process_group(group_id)
if self._batch_size(bkey) >= self.batch_size_for(cancellation.env_name):
return self.process_batch(bkey)
return None
def _group_size(self, group_id: str) -> int:
return len(self.pending_groups[group_id]) + len(self.pending_group_failures[group_id])
cancellation = self.pending_group_cancellations.get(group_id)
return (
len(self.pending_groups[group_id])
+ len(self.pending_group_failures[group_id])
+ (cancellation.count if cancellation is not None else 0)
)
def _batch_size(self, key: tuple[str, int]) -> int:
return len(self.pending_batches[key]) + len(self.pending_batch_failures[key])
return (
len(self.pending_batches[key])
+ len(self.pending_batch_failures[key])
+ self.pending_batch_cancellations[key]
)
def group_size_for(self, env_name: str) -> int:
return self.eval_envs.get(env_name).config.group_size
@@ -64,23 +88,32 @@ class EvalSink:
return len(env.examples) * env.config.group_size
def batch_progress(self) -> list[tuple[str, int, int, int, int]]:
keys = set(self.pending_batches) | set(self.pending_batch_failures)
keys = set(self.pending_batches) | set(self.pending_batch_failures) | set(self.pending_batch_cancellations)
batch_counts = {key: self._batch_size(key) for key in keys}
buffered: dict[tuple[str, int], int] = {}
group_ids = set(self.pending_groups) | set(self.pending_group_failures)
group_ids = set(self.pending_groups) | set(self.pending_group_failures) | set(self.pending_group_cancellations)
for group_id in group_ids:
group = self.pending_groups[group_id]
failures = self.pending_group_failures[group_id]
if not group and not failures:
cancellation = self.pending_group_cancellations.get(group_id)
if not group and not failures and cancellation is None:
continue
if group:
env_name = episode_env_name(group[0])
eval_step = eval_work(group[0]).step
else:
elif failures:
env_name = failures[0].env_name
eval_step = failures[0].step
else:
env_name = cancellation.env_name
eval_step = cancellation.step
key = (env_name, eval_step)
buffered[key] = buffered.get(key, 0) + len(group) + len(failures)
buffered[key] = (
buffered.get(key, 0)
+ len(group)
+ len(failures)
+ (cancellation.count if cancellation is not None else 0)
)
return [
(
env_name,
@@ -95,17 +128,23 @@ class EvalSink:
def process_group(self, group_id: str) -> None:
group = self.pending_groups.pop(group_id, [])
failures = self.pending_group_failures.pop(group_id, [])
if not group and not failures:
cancellation = self.pending_group_cancellations.pop(group_id, None)
if not group and not failures and cancellation is None:
return
if group:
env_name = episode_env_name(group[0])
eval_step = eval_work(group[0]).step
else:
elif failures:
env_name = failures[0].env_name
eval_step = failures[0].step
else:
env_name = cancellation.env_name
eval_step = cancellation.step
key = (env_name, eval_step)
self.pending_batches[key].extend(group)
self.pending_batch_failures[key].extend(failures)
if cancellation is not None:
self.pending_batch_cancellations[key] += cancellation.count
traces = [trace for episode in group for trace in episode.traces]
survivors = [trace for trace in traces if not trace.has_error]
@@ -116,6 +155,7 @@ class EvalSink:
get_logger().debug(
f"Finished group | env={env_name} task_idx={task_idx} "
f"eval_step={eval_step} | episodes={len(group)} dispatch_failures={len(failures)} "
f"cancelled={cancellation.count if cancellation is not None else 0} "
f"traces={len(traces)} (errored={num_errored + len(failures)}) | reward={avg_reward:.4f}"
)
@@ -123,9 +163,11 @@ class EvalSink:
env_name, step = key
episodes = self.pending_batches.pop(key, [])
failures = self.pending_batch_failures.pop(key, [])
cancelled = self.pending_batch_cancellations.pop(key, 0)
return EvalBatch(
env_name=env_name,
step=step,
episodes=EvalEpisodes(episodes, group_size=self.group_size_for(env_name)),
failures=failures,
cancelled=cancelled,
)
+6
View File
@@ -71,6 +71,12 @@ class EvalSource:
return None
return self.queue.popleft()
def cancel_step(self, step: int) -> list[TaskRequest]:
"""Remove and return queued examples for a superseded eval step."""
cancelled = [request for request in self.queue if request.step == step]
self.queue = deque(request for request in self.queue if request.step != step)
return cancelled
def __bool__(self) -> bool:
return bool(self.queue)
+4 -2
View File
@@ -35,7 +35,7 @@ class Progress:
WorkKind = Literal["train", "eval"]
CancelReason = Literal["stale", "overload"]
CancelReason = Literal["stale", "overload", "superseded"]
@dataclass
@@ -43,11 +43,12 @@ class GroupCancellation:
"""Terminal marker for a dropped group: one message covering every episode
the group still owed the sink (in-flight and never-dispatched), so
count-to-``group_size`` finalization still fires. ``reason`` distinguishes
pipeline decisions (staleness, overload cut) from episode errors."""
pipeline decisions (staleness, overload cut, superseded eval) from episode errors."""
kind: WorkKind
env_name: str
group_id: str
step: int
count: int
reason: CancelReason
@@ -131,6 +132,7 @@ class EvalBatch:
step: int
episodes: EvalEpisodes
failures: list[DispatchFailure]
cancelled: int = 0
class VersionObserver(Protocol):