File size: 16,895 Bytes
1e9e3f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
"""Periodic mid-run evaluation for GRPO (greedy eval on a held-out split, between steps).

GRPO's only live signal is the per-step *training* reward β€” noisy, on-policy, temperature>0,
and (by design) often a SHAPED reward rather than the metric you actually care about. This
module adds a deterministic eval signal: every ``N`` optimizer steps it samples the current
policy GREEDILY on a fixed held-out split and scores it, then streams the result through the
worker ``heartbeat`` so the orchestrating agent sees an eval curve mid-run (early-stop, plateau
detection, checkpoint selection) instead of only the reward stream.

Evaluation distinct from reward lives in the env, not a separate ``eval.py``. A verifiers
``environment.py`` expresses an evaluation metric SEPARATE from the GRPO reward as a
**zero-weight rubric func** (``rubric.add_metric(fn, weight=0.0)``): it does not shape training
but is computed and reported. The adapter's :meth:`VerifiersEnvironment.evaluate` returns both
the weighted training ``reward`` and those zero-weight ``metrics`` in one rubric pass, and this
module surfaces both β€” so the agent watches the env's true eval metric, not just the reward.

It generates with the **trainer's own model** (``trainer.model.generate`` in eval/no-grad mode),
NOT the colocate vLLM engine. Calling ``engine.generate`` out-of-band from a ``TrainerCallback``
deadlocks GRPO (the engine is only safe to drive inside TRL's managed ``rollout_func`` window;
an external call from ``on_step_end`` hangs the training thread β€” verified on a live GPU run).
Generating on the already-loaded trainer model avoids the engine entirely, works on BOTH the
vLLM-colocate and transformers-generation backends, and keeps memory bounded: ONE prompt at a
time (a single sequence's KV cache), and an OOM there is a *catchable* error -> graceful
``eval_skipped``, never a training-freezing hang.

Design mirrors :mod:`autoslm.engine.multiturn_rollout`: the core (:class:`PeriodicEval`, the
scorers, :func:`evaluate_policy`, :func:`summarize`) is pure Python with ``render`` / ``generate``
/ engine access INJECTED, so cadence gating, engine binding, skip handling and heartbeat
emission are unit-tested without a GPU, tokenizer, or vLLM. Only :func:`build_hf_greedy_generate`
(wired in ``worker.run_rl``) touches torch / the live model.
"""

from __future__ import annotations

import os
from collections.abc import Callable
from dataclasses import dataclass, field

from autoslm.engine.multiturn_rollout import rollout_one

# A failed single rollout (template violation, env exception) scores 0 rather than crashing the
# whole eval β€” and a crashing eval must never abort a paid training run, so the callback also
# swallows eval-wide failures and heartbeats a skip reason.
_EVAL_ERROR_REWARD = 0.0


@dataclass(frozen=True)
class EvalRecord:
    """One example's eval result: the training ``reward`` and the env's zero-weight ``metrics``."""

    reward: float
    metrics: dict[str, float] = field(default_factory=dict)


@dataclass(frozen=True)
class EvalSummary:
    """Aggregate of one mid-run eval pass over the held-out set."""

    n: int
    mean_reward: float
    pass_rate: float
    min_reward: float
    max_reward: float
    metric_means: dict[str, float] = field(default_factory=dict)
    rewards: list[float] = field(default_factory=list)
    step: int | None = None

    def as_heartbeat_fields(self) -> dict:
        """The flat fields streamed under the ``rl_eval`` heartbeat stage. Each env eval metric
        is reported as ``eval_metric_<name>`` so it sits alongside the reward, distinct from it."""
        fields: dict[str, float | int] = {
            "eval_n": self.n,
            "eval_reward": self.mean_reward,
            "eval_pass_rate": self.pass_rate,
            "eval_reward_min": self.min_reward,
            "eval_reward_max": self.max_reward,
        }
        for name, value in self.metric_means.items():
            fields[f"eval_metric_{name}"] = value
        return fields


def summarize(
    records: list[EvalRecord], *, step: int | None = None, pass_threshold: float = 0.5
) -> EvalSummary:
    """Reduce per-example records to an :class:`EvalSummary` (empty -> all-zero, n=0).

    ``pass_rate`` is the fraction with training ``reward >= pass_threshold``; each env metric is
    averaged independently across the examples that reported it.
    """
    if not records:
        return EvalSummary(0, 0.0, 0.0, 0.0, 0.0, {}, [], step)
    rewards = [float(r.reward) for r in records]
    n = len(rewards)
    metric_sums: dict[str, float] = {}
    metric_counts: dict[str, int] = {}
    for rec in records:
        for name, value in rec.metrics.items():
            metric_sums[name] = metric_sums.get(name, 0.0) + float(value)
            metric_counts[name] = metric_counts.get(name, 0) + 1
    metric_means = {name: metric_sums[name] / metric_counts[name] for name in metric_sums}
    return EvalSummary(
        n=n,
        mean_reward=sum(rewards) / n,
        pass_rate=sum(1 for r in rewards if r >= pass_threshold) / n,
        min_reward=min(rewards),
        max_reward=max(rewards),
        metric_means=metric_means,
        rewards=rewards,
        step=step,
    )


def evaluate_policy(
    examples: list[dict],
    score_one: Callable[[dict], EvalRecord],
    *,
    step: int | None = None,
    pass_threshold: float = 0.5,
    on_error: str = "zero",
    on_warn: Callable[[str], None] | None = None,
) -> EvalSummary:
    """Score every example with ``score_one`` and summarize.

    ``on_error="zero"`` (default) makes a per-example scoring failure a zero-reward record (so
    one bad rollout doesn't sink the pass); ``on_error="raise"`` re-raises (tests).

    A SYSTEMIC failure (every example errors β€” e.g. generation OOMs each call) raises instead of
    returning ``eval_reward=0``: a flat-zero curve reads as "the model got everything wrong",
    which is misleading when the eval simply couldn't run. The caller turns that into a skip.
    """
    records: list[EvalRecord] = []
    errors = 0
    last_error: Exception | None = None
    for ex in examples:
        try:
            records.append(score_one(ex))
        except Exception as exc:  # a bad rollout must not abort the eval/run
            if on_error == "raise":
                raise
            errors += 1
            last_error = exc
            if on_warn:
                on_warn(f"mid-run eval: example scored 0 after error: {exc}")
            records.append(EvalRecord(_EVAL_ERROR_REWARD, {}))
    if examples and errors == len(examples):
        raise RuntimeError(
            f"mid-run eval: all {errors} examples failed to generate "
            f"(last error: {last_error}) β€” reporting a skip, not eval_reward=0"
        )
    return summarize(records, step=step, pass_threshold=pass_threshold)


def single_turn_scorer(
    active_env,
    render_prompt_ids: Callable[[dict], list[int]],
    generate: Callable[[list[int], int], tuple[list[int], list[float], str]],
    max_new_tokens: int,
    graded_text: Callable[[str | None], str | None] = lambda c: c,
) -> Callable[[dict], EvalRecord]:
    """Per-example scorer for a single-turn env: render -> greedy generate -> env evaluate.

    ``generate(prefix_ids, max_tokens) -> (token_ids, logprobs, text)`` mirrors the colocate
    engine wrapper used by the multi-turn rollout; only ``text`` is used here. ``graded_text``
    strips ``<think>`` blocks before scoring on thinking runs (worker parity). Uses the env's
    :meth:`evaluate` so the env's zero-weight metrics come back alongside the reward."""

    def score(example: dict) -> EvalRecord:
        prefix_ids = render_prompt_ids(example)
        _ids, _lps, text = generate(prefix_ids, max_new_tokens)
        result = active_env.evaluate(graded_text(text), example)
        return EvalRecord(
            reward=float(result["reward"]),
            metrics={k: float(v) for k, v in (result.get("metrics") or {}).items()},
        )

    return score


def multi_turn_scorer(
    active_env,
    render_messages: Callable[[list, bool], list[int]],
    generate: Callable[[list[int], int], tuple[list[int], list[float], str]],
    *,
    max_turns: int,
    max_new_tokens: int,
    engine_max_len: int | None = None,
    on_warn: Callable[[str], None] | None = None,
) -> Callable[[dict], EvalRecord]:
    """Per-example scorer for a multi-turn env: drive the env turn loop GREEDILY via
    :func:`rollout_one` and read its rubric reward. (Per-metric breakdown for multi-turn is a
    follow-up β€” ``rollout_one`` returns only the scalar reward β€” so ``metrics`` is empty here.)"""

    def score(example: dict) -> EvalRecord:
        result = rollout_one(
            example=example,
            active_env=active_env,
            render=render_messages,
            generate=generate,
            max_turns=max_turns,
            per_turn_max_tokens=max_new_tokens,
            engine_max_len=engine_max_len,
            on_warn=on_warn,
        )
        return EvalRecord(reward=float(result["reward"]), metrics={})

    return score


class PeriodicEval:
    """Pure cadence + engine-binding + heartbeat logic for mid-run eval (no GPU/transformers).

    ``score_one_builder(engine) -> score_one`` defers all GPU-specific wiring (the vLLM
    SamplingParams, the tokenizer render) to call time, so this class is fully unit-testable
    with a fake engine getter, a fake builder, and a fake heartbeat sink.
    """

    def __init__(
        self,
        *,
        examples: list[dict],
        score_one_builder: Callable[[object], Callable[[dict], EvalRecord]],
        every_steps: int,
        heartbeat_fn: Callable[..., object],
        engine_getter: Callable[[], object] | None = None,
        pass_threshold: float = 0.5,
        label: str = "rl_eval",
        on_warn: Callable[[str], None] = print,
    ) -> None:
        self.examples = list(examples)
        self.score_one_builder = score_one_builder
        self.every_steps = int(every_steps)
        self.heartbeat_fn = heartbeat_fn
        self.engine_getter = engine_getter
        self.pass_threshold = float(pass_threshold)
        self.label = label
        self.on_warn = on_warn
        self._disabled = False

    def bind_engine_getter(self, getter: Callable[[], object]) -> None:
        """Attach the (late-bound) accessor for the colocate engine β€” the trainer that owns it
        does not exist when the callback is constructed."""
        self.engine_getter = getter

    def should_run(self, step: int) -> bool:
        return (
            not self._disabled
            and self.every_steps > 0
            and step > 0
            and bool(self.examples)
            and step % self.every_steps == 0
        )

    def maybe_run(self, step: int) -> EvalSummary | None:
        if not self.should_run(step):
            return None
        return self.run_eval(step)

    def run_eval(self, step: int) -> EvalSummary | None:
        """Evaluate the current policy once and heartbeat the result (or a skip reason).

        Never raises (even if the model getter itself throws): any failure heartbeats a skip
        reason for THIS step and lets training continue. A missing model only skips this cadence
        β€” it does NOT permanently disable eval, since the getter resolves the live model each
        time and a one-off ``None`` (e.g. a teardown race) can resolve by the next cadence.
        """
        try:
            model = self.engine_getter() if self.engine_getter is not None else None
        except Exception as exc:  # the getter (attribute access on the trainer) must not abort
            self.heartbeat_fn(
                self.label, step=step, eval_skipped=True, eval_reason=f"model getter failed: {exc}"
            )
            return None
        if model is None:
            self.heartbeat_fn(
                self.label, step=step, eval_skipped=True, eval_reason="no model available"
            )
            return None
        try:
            score_one = self.score_one_builder(model)
            summary = evaluate_policy(
                self.examples,
                score_one,
                step=step,
                pass_threshold=self.pass_threshold,
                on_warn=self.on_warn,
            )
        except Exception as exc:  # eval must never abort training
            self.heartbeat_fn(
                self.label,
                step=step,
                eval_skipped=True,
                eval_reason=f"{type(exc).__name__}: {exc}",
            )
            return None
        self.heartbeat_fn(self.label, step=step, **summary.as_heartbeat_fields())
        return summary


def make_periodic_eval_callback(periodic: PeriodicEval):
    """Wrap a :class:`PeriodicEval` in a transformers ``TrainerCallback`` (lazy import).

    Mirrors ``worker.make_reward_heartbeat_callback``: the callback fires on every optimizer
    step end and delegates the cadence decision to ``periodic.maybe_run``."""
    from transformers import TrainerCallback

    class _PeriodicEvalCallback(TrainerCallback):
        def on_step_end(self, args, state, control, **kwargs):
            step = int(getattr(state, "global_step", 0) or 0)
            periodic.maybe_run(step)

    return _PeriodicEvalCallback()


# ---------------------------------------------------------------------------
# GPU-side wiring (the only part that touches torch / the model). From worker.run_rl.
# ---------------------------------------------------------------------------
def eval_config_from_env(default_max_new: int) -> dict:
    """Read the mid-run-eval knobs off the environment (idiomatic with the rest of worker.py).

    ``AUTOSLM_EVAL_EVERY_STEPS`` (default 0 = disabled) is the only switch that turns the
    feature on; the rest have sensible defaults.
    """
    # Bound each knob: a negative AUTOSLM_EVAL_NUM would hit Python's negative-slicing semantics
    # (examples[:-3] silently evals nearly the whole split); a non-positive max_new is clamped to
    # at least 1 token. every_steps<=0 disables (handled by the caller).
    return {
        "every_steps": int(os.environ.get("AUTOSLM_EVAL_EVERY_STEPS", "0") or 0),
        "num_examples": max(0, int(os.environ.get("AUTOSLM_EVAL_NUM", "32") or 32)),
        "max_new_tokens": max(1, int(os.environ.get("AUTOSLM_EVAL_MAX_NEW", str(default_max_new)))),
        "pass_threshold": float(os.environ.get("AUTOSLM_EVAL_PASS_THRESHOLD", "0.5")),
    }


def build_hf_greedy_generate(
    model, tok, *, stop: list[str] | None
) -> Callable[[list[int], int], tuple[list[int], list[float], str]]:
    """A greedy (deterministic) generate over the TRAINER'S model via ``transformers.generate``,
    returning ``(token_ids, logprobs, text)`` like the multi-turn rollout's generate.

    Uses the model directly (NOT the colocate vLLM engine, whose out-of-band use from a callback
    hangs GRPO). Runs in eval + ``no_grad`` and restores train mode; ``use_cache=True`` is forced
    so generation works even when training has it off under gradient checkpointing (no backward
    happens here, so checkpointing is irrelevant). One prompt at a time keeps the KV footprint to
    a single sequence; an OOM raises (caught upstream -> ``eval_skipped``), never hangs.

    Stop sequences are honored via ``stop_strings`` so generation actually STOPS at the stop
    (rather than post-hoc truncating the text only) β€” this keeps the returned ``token_ids`` and
    ``text`` in lockstep (``text == decode(token_ids)``), which the multi-turn ``rollout_one``
    prefix invariant requires; truncating text alone would desync them."""
    import torch

    pad_id = tok.pad_token_id if tok.pad_token_id is not None else tok.eos_token_id
    stop_kwargs = {"stop_strings": list(stop), "tokenizer": tok} if stop else {}

    def generate(prefix_ids: list[int], max_tokens: int):
        input_ids = torch.tensor([list(prefix_ids)], dtype=torch.long, device=model.device)
        was_training = model.training
        try:
            model.eval()
            with torch.no_grad():
                out = model.generate(
                    input_ids,
                    attention_mask=torch.ones_like(input_ids),
                    max_new_tokens=max(1, int(max_tokens)),
                    do_sample=False,  # greedy / deterministic eval
                    use_cache=True,
                    pad_token_id=pad_id,
                    **stop_kwargs,
                )
        finally:
            if was_training:
                model.train()
        # text == decode(new_ids): never post-hoc truncate one without the other (see docstring).
        new_ids = [int(t) for t in out[0][input_ids.shape[1] :].tolist()]
        text = tok.decode(new_ids, skip_special_tokens=True)
        return new_ids, [0.0] * len(new_ids), text

    return generate