verifiers 0.4.1.dev79__py3-none-any.whl → 0.4.1.dev80__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ from verifiers.v1.envs.best_of_n_judge.env import (
2
+ BestOfNJudgeEnv,
3
+ BestOfNJudgeEnvConfig,
4
+ RankTask,
5
+ RankTaskConfig,
6
+ )
7
+
8
+ __all__ = ["BestOfNJudgeEnv", "BestOfNJudgeEnvConfig", "RankTask", "RankTaskConfig"]
@@ -0,0 +1,345 @@
1
+ """best-of-n-judge: n attempts at the task, ranked side by side by agentic judges.
2
+
3
+ The "agent" role attempts the task `--env.n` times, as in best-of-n. A judge then
4
+ gets a fresh sandbox from the task's image holding every attempt's trace record
5
+ and collected artifacts under shuffled labels, verifies them empirically, and
6
+ writes a best-to-worst ranking. `--env.judges` runs that many independent judges
7
+ (an ensemble, each with its own shuffle); an attempt's `judge` reward is its rank
8
+ score averaged across them.
9
+ """
10
+
11
+ import asyncio
12
+ import json
13
+ import random
14
+ import shlex
15
+ import statistics
16
+ import uuid
17
+
18
+ from pydantic import BaseModel, ConfigDict, Field
19
+
20
+ import verifiers.v1 as vf
21
+ from verifiers.v1.envs.agentic_judge.env import (
22
+ VERDICT_FILE,
23
+ JudgeTaskConfig,
24
+ ScoreConfig,
25
+ TextSource,
26
+ )
27
+ from verifiers.v1.envs.best_of_n import BestOfNEnv, BestOfNEnvConfig
28
+ from verifiers.v1.runtimes import backend_cls
29
+ from verifiers.v1.utils.artifacts import _validate_restore
30
+
31
+ ATTEMPTS_DIR = "/tmp/attempts"
32
+ # Shuffles stay independent of the global `random`, which tasksets may seed.
33
+ _SHUFFLE = random.SystemRandom()
34
+
35
+ RANK_PROMPT = """\
36
+ You are comparing several attempts at the same task and ranking them from best
37
+ to worst. Verify the work EMPIRICALLY: reconstruct what each attempt did from its
38
+ trace and artifacts, and test its output with real execution in your sandbox —
39
+ never take a trace's word for an outcome you can check.
40
+
41
+ ## The task the attempts were given
42
+
43
+ {prompt}"""
44
+
45
+ HINT_SECTION = """\
46
+ ## Hints
47
+
48
+ {hint}"""
49
+
50
+ WORKSPACE_NOTE = f"""\
51
+ ## Your workspace
52
+
53
+ This is a fresh sandbox from the task's image; no attempt ran in it. Each attempt
54
+ has its own directory, `{ATTEMPTS_DIR}/<label>/`, labelled in random order:
55
+
56
+ - `trace.json`: the attempt's observable trace record (JSON: messages, tool
57
+ calls, and its `info` artifacts), written by the harness — not the attempt. It
58
+ can be very large — never dump it whole; list its keys, then slice out specific
59
+ fields with python or jq. Hidden reasoning and opaque provider state are not
60
+ included. It may also carry the task's own
61
+ scores and reference material: context, not your standard. Your ranking is what
62
+ YOU verified by execution.
63
+ - `artifacts/`: the files the attempt published, each at its original absolute
64
+ path (`/app/answer.txt` is at `artifacts/app/answer.txt`). Absent when the
65
+ attempt published none.
66
+
67
+ To test an attempt's output, copy it to where the task expects it, and restore
68
+ that state before testing the next attempt."""
69
+
70
+
71
+ def _verdict_section(labels: list[str]) -> str:
72
+ listing = ", ".join(labels)
73
+ return f"""\
74
+ ## Your verdict
75
+
76
+ The attempts are {listing}. When you are done verifying, write your ranking as
77
+ JSON to `{VERDICT_FILE}`:
78
+
79
+ {{"ranking": [["<best label>"], ["<label>", "<label tied with it>"], ...],
80
+ "reasons": {{"<label>": "<one sentence citing what you verified>", ...}}}}
81
+
82
+ `ranking` lists tiers from best to worst; attempts of equal quality share a tier.
83
+ Name every attempt exactly once, leave no tier empty, and give every attempt a
84
+ reason."""
85
+
86
+
87
+ class Ranking(BaseModel):
88
+ """A judge's verdict: best-to-worst tiers of attempt labels, ties sharing one."""
89
+
90
+ model_config = ConfigDict(extra="forbid")
91
+
92
+ ranking: list[list[str]]
93
+ reasons: dict[str, str]
94
+
95
+ def check(self, labels: list[str]) -> None:
96
+ ranked = [label for tier in self.ranking for label in tier]
97
+ if any(not tier for tier in self.ranking) or sorted(ranked) != sorted(labels):
98
+ raise ValueError(
99
+ f"the ranking must name each of {labels} exactly once in nonempty "
100
+ f"tiers, got {self.ranking}"
101
+ )
102
+ if sorted(self.reasons) != sorted(labels):
103
+ raise ValueError(
104
+ f"the reasons must cover exactly {labels}, got {sorted(self.reasons)}"
105
+ )
106
+
107
+ def scores(self) -> dict[str, float]:
108
+ """Each attempt's share of the others it beats, a tie counting half: a sole
109
+ best scores 1, a sole worst 0, and an all-tied ranking 0.5 each."""
110
+ count = sum(len(tier) for tier in self.ranking)
111
+ below = count
112
+ scores = {}
113
+ for tier in self.ranking:
114
+ below -= len(tier)
115
+ score = (below + (len(tier) - 1) / 2) / (count - 1)
116
+ scores.update(dict.fromkeys(tier, score))
117
+ return scores
118
+
119
+
120
+ class RankTask(vf.Task):
121
+ """One judge's ranking task: every attempt's record and artifacts uploaded
122
+ under its label before the judge starts, the ranking scraped off the box after
123
+ it exits. `NEEDS_CONTAINER`: the judge executes code, never on the host."""
124
+
125
+ NEEDS_CONTAINER = True
126
+
127
+ def __init__(self, data: vf.TaskData, labels: dict[str, vf.Trace]) -> None:
128
+ super().__init__(data)
129
+ self.labels = labels
130
+
131
+ @staticmethod
132
+ def record(attempt: vf.Trace) -> bytes:
133
+ record = attempt.to_record()
134
+ # This snapshot is evidence for verification, not its final outcome.
135
+ record.pop("ok", None)
136
+ for node in record["nodes"]:
137
+ node["message"].pop("reasoning_content", None)
138
+ node["message"].pop("provider_state", None)
139
+ return json.dumps(record).encode()
140
+
141
+ async def setup(self, trace: vf.Trace, runtime: vf.Runtime) -> None:
142
+ # Archive bytes are the attempts': confine every member to its declared
143
+ # root before anything lands in the judge's box.
144
+ for attempt in self.labels.values():
145
+ for source, archive in attempt.state.artifacts.items():
146
+ _validate_restore(source, archive)
147
+ await runtime.run(["rm", "-rf", ATTEMPTS_DIR, VERDICT_FILE], env={})
148
+ for label, attempt in self.labels.items():
149
+ root = f"{ATTEMPTS_DIR}/{label}"
150
+ await runtime.write(f"{root}/trace.json", self.record(attempt))
151
+ for source, archive in attempt.state.artifacts.items():
152
+ if archive is None:
153
+ continue
154
+ upload = f"/tmp/vf-attempt-{uuid.uuid4().hex}.tar"
155
+ await runtime.write(upload, archive)
156
+ target = shlex.quote(f"{root}/artifacts")
157
+ unpack = (
158
+ f"mkdir -p {target} && tar -xf {upload} -C {target} "
159
+ f"&& rm -f {upload}"
160
+ )
161
+ result = await runtime.run(["sh", "-c", unpack], env={})
162
+ if result.exit_code:
163
+ raise RuntimeError(
164
+ f"failed to unpack attempt {label}'s artifact {source!r}: "
165
+ f"{(result.stderr or result.stdout).strip()[-500:]}"
166
+ )
167
+
168
+ async def finalize(self, trace: vf.Trace, runtime: vf.Runtime) -> None:
169
+ """Scrape the ranking off the box while it's alive. A judge that wrote no
170
+ valid ranking fails HERE — on its own trace, the retryable unit."""
171
+ try:
172
+ raw = await runtime.read(VERDICT_FILE)
173
+ except Exception as e:
174
+ raise ValueError(
175
+ f"the judge wrote no ranking to {VERDICT_FILE}; its final act must be "
176
+ 'writing {"ranking": [[...], ...], "reasons": {...}} there'
177
+ ) from e
178
+ ranking = Ranking.model_validate_json(raw)
179
+ ranking.check(list(self.labels))
180
+ trace.info["ranking"] = {
181
+ "attempts": {label: attempt.id for label, attempt in self.labels.items()},
182
+ **ranking.model_dump(),
183
+ "scores": {
184
+ self.labels[label].id: score
185
+ for label, score in ranking.scores().items()
186
+ },
187
+ }
188
+
189
+
190
+ class RankTaskConfig(vf.BaseConfig):
191
+ """The judges' minted task: the ranking policy and what lands in their box."""
192
+
193
+ prompt: TextSource | None = None
194
+ """Ranking policy: a string is inline text; a `Path` in Python or
195
+ `{ path = "policy.md" }` in config reads a file. Replaces only the policy
196
+ body — the verdict contract and workspace note are always appended. May
197
+ reference `{prompt}` (the attempts' task); if it doesn't, the task statement
198
+ is appended after."""
199
+ hint: TextSource | None = None
200
+ """Optional hints, with the same inline/file forms as `prompt`, injected as
201
+ their own section."""
202
+
203
+ def build_policy(self) -> str:
204
+ if self.prompt is None:
205
+ return RANK_PROMPT
206
+ return JudgeTaskConfig._resolve(self.prompt)
207
+
208
+ def build_hint(self) -> str | None:
209
+ return JudgeTaskConfig._resolve(self.hint) if self.hint is not None else None
210
+
211
+ def build_prompt(self, task: vf.TaskData, labels: list[str]) -> str:
212
+ statement = "\n\n".join(
213
+ text for text in (task.system_prompt, task.prompt_text) if text
214
+ )
215
+ template = self.build_policy()
216
+ body = template.replace("{prompt}", statement)
217
+ if "{prompt}" not in template:
218
+ # A policy that doesn't place the task statement itself still needs it.
219
+ body += "\n\n## The task the attempts were given\n\n" + statement
220
+ sections = [body, _verdict_section(labels), WORKSPACE_NOTE]
221
+ if (hint := self.build_hint()) is not None:
222
+ sections.insert(1, HINT_SECTION.replace("{hint}", hint))
223
+ return "\n\n".join(sections)
224
+
225
+
226
+ class BestOfNJudgeEnvConfig(BestOfNEnvConfig):
227
+ n: int = Field(4, ge=2)
228
+ """Independent attempts per episode, ranked against each other."""
229
+ judge: vf.AgentConfig = vf.AgentConfig()
230
+ """The judge program; each judge gets a fresh container from the task's image."""
231
+ judges: int = Field(1, ge=1)
232
+ """Independent judges per episode (the ensemble); each ranks its own shuffle."""
233
+ task: RankTaskConfig = RankTaskConfig()
234
+ score: ScoreConfig = ScoreConfig()
235
+
236
+
237
+ class BestOfNJudgeEnv(BestOfNEnv, vf.Env[BestOfNJudgeEnvConfig]):
238
+ config: BestOfNJudgeEnvConfig
239
+
240
+ def __init__(self, config: BestOfNJudgeEnvConfig) -> None:
241
+ super().__init__(config)
242
+ # A missing policy file fails here, not mid-episode.
243
+ config.task.build_policy()
244
+ config.task.build_hint()
245
+ # Refuse an impossible judge at construction, not after n attempts ran.
246
+ judge = self._harnesses["judge"]
247
+ if not judge.EXECUTES_CODE:
248
+ raise ValueError(
249
+ "best-of-n-judge requires a judge harness that can execute code, but "
250
+ f"harness {judge.config.id!r} is a tool-less chat loop"
251
+ )
252
+ if not backend_cls(config.judge.runtime).SUPPORTS_TASK_IMAGES:
253
+ raise ValueError(
254
+ "best-of-n-judge requires a container judge runtime: "
255
+ "--env.judge.runtime.type docker|prime"
256
+ )
257
+
258
+ async def setup(self, agents: vf.Agents) -> None:
259
+ # The judges grade the policy; their tokens are never training data.
260
+ agents.judge.trainable = False
261
+
262
+ async def run(self, task: vf.Task, agents: vf.Agents) -> None:
263
+ # Artifacts need a runtime with its own filesystem; a subprocess attempt
264
+ # is ranked on its trace alone.
265
+ collect = backend_cls(self.config.agent.runtime).SUPPORTS_TASK_IMAGES
266
+ async with asyncio.TaskGroup() as tg:
267
+ runs = [
268
+ tg.create_task(agents.agent.run(task, collect_artifacts=collect))
269
+ for _ in range(self.config.n)
270
+ ]
271
+ attempts = [run.result() for run in runs]
272
+ for attempt in attempts:
273
+ attempt.record_metric("task_reward", attempt.reward)
274
+ if not all(attempt.ok for attempt in attempts):
275
+ # A failed attempt already fails the episode, and trainers skip failed
276
+ # episodes whole: a ranking of the rest would be spent for nothing.
277
+ return
278
+ async with asyncio.TaskGroup() as tg:
279
+ judged = [
280
+ tg.create_task(self._rank(task, attempts, agents))
281
+ for _ in range(self.config.judges)
282
+ ]
283
+ rankings = [run.result() for run in judged]
284
+ for attempt in attempts:
285
+ score = statistics.fmean(ranking[attempt.id] for ranking in rankings)
286
+ if self.config.score.task_weight != 1.0:
287
+ for reward in attempt.rewards.values():
288
+ if reward is not None:
289
+ reward.weight *= self.config.score.task_weight
290
+ attempt.record_reward("judge", score, weight=self.config.score.judge_weight)
291
+
292
+ async def _rank(
293
+ self, task: vf.Task, attempts: list[vf.Trace], agents: vf.Agents
294
+ ) -> dict[str, float]:
295
+ """One judge's rank scores, keyed by attempt trace id."""
296
+ shuffled = _SHUFFLE.sample(attempts, len(attempts))
297
+ labels = dict(zip(_labels(len(shuffled)), shuffled))
298
+ verdict = await agents.judge.run(self.make_rank_task(task, labels))
299
+ if not verdict.ok:
300
+ raise RuntimeError(
301
+ "best-of-n judge failed: "
302
+ + "; ".join(error.message for error in verdict.errors)
303
+ )
304
+ return verdict.info["ranking"]["scores"]
305
+
306
+ def make_rank_task(self, task: vf.Task, labels: dict[str, vf.Trace]) -> RankTask:
307
+ """One judge's task over the labelled attempts. Override to change what
308
+ the judge sees (e.g. native image parts), or to return a RankTask subclass
309
+ whose `setup` also rebuilds the task's world: a fresh box from the task's
310
+ image doesn't replay the task's own setup."""
311
+ data = task.data
312
+ return RankTask(
313
+ vf.TaskData(
314
+ idx=data.idx,
315
+ prompt=self.config.task.build_prompt(data, list(labels)),
316
+ image=data.image,
317
+ workdir=data.workdir,
318
+ resources=data.resources,
319
+ network=data.network,
320
+ ),
321
+ labels,
322
+ )
323
+
324
+ async def finalize(self, task: vf.Task, episode: vf.Episode) -> None:
325
+ """best-of-n's sibling metrics over the attempts alone: `best` marks the
326
+ attempt with the top final (judged) reward, `pass_at_n` whether any
327
+ attempt's own task reward reached the threshold."""
328
+ attempts = [t for t in episode.traces if t.agent.name == "agent"]
329
+ top = max(t.reward for t in attempts)
330
+ solved = float(
331
+ max(t.metrics["task_reward"] or 0.0 for t in attempts)
332
+ >= self.config.threshold
333
+ )
334
+ for trace in attempts:
335
+ trace.record_metric("best", float(trace.reward == top))
336
+ trace.record_metric("pass_at_n", solved)
337
+
338
+
339
+ def _labels(count: int) -> list[str]:
340
+ """Distinct random hex labels, three digits unless more attempts need more,
341
+ so a label hints at neither an attempt's index nor its listing position."""
342
+ width = 3
343
+ while 16**width < count:
344
+ width += 1
345
+ return [f"{i:0{width}x}" for i in _SHUFFLE.sample(range(16**width), count)]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: verifiers
3
- Version: 0.4.1.dev79
3
+ Version: 0.4.1.dev80
4
4
  Summary: Verifiers: Environments for LLM Reinforcement Learning
5
5
  Project-URL: Homepage, https://github.com/primeintellect-ai/verifiers
6
6
  Project-URL: Documentation, https://github.com/primeintellect-ai/verifiers
@@ -73,6 +73,8 @@ verifiers/v1/envs/agentic_judge/__init__.py,sha256=6vwtMCQ_cuvuubCF5-nrE5W7gGgzE
73
73
  verifiers/v1/envs/agentic_judge/env.py,sha256=WLvEvM7bgTieCvOtmOLb-2RmWOwpMAd3m0GZuitUCzc,14956
74
74
  verifiers/v1/envs/best_of_n/__init__.py,sha256=mubASiwXMNIhnQFDccNAc7yZ0OFsOVK8hH8WIx9b2A4,119
75
75
  verifiers/v1/envs/best_of_n/env.py,sha256=KEUJBCVqblnXP_lEwm3mjGdaikBMkecz8UjOFPBhxc0,1987
76
+ verifiers/v1/envs/best_of_n_judge/__init__.py,sha256=xEe_uG3CHVa4psZOkbrQV8u9u63HK1iR-jvtuknUZOw,222
77
+ verifiers/v1/envs/best_of_n_judge/env.py,sha256=2jb2wbiGQ9HWAOqBKDkdtkUnzdyfJWUxTqbTiYPMha8,14756
76
78
  verifiers/v1/envs/single_agent/__init__.py,sha256=r0edAc_6gtHBhPzeBGVcdHZZqSdCPZnLMje6eVgyz5U,138
77
79
  verifiers/v1/envs/single_agent/env.py,sha256=iH-AnS5-5rDZM3MaYFxzaHSVqJAaw9mQJaaJvsDMMX4,854
78
80
  verifiers/v1/envs/user_sim/__init__.py,sha256=nnT695HdqjAEouYL5wtVu6MhIp2wf5yuK-EYgxOVx0s,118
@@ -205,8 +207,8 @@ verifiers/v1/utils/scope.py,sha256=bzUEiWDOVdbj7dXOwGOlzsQ_-Xu0j9NR5TalQB-8TS8,8
205
207
  verifiers/v1/utils/score.py,sha256=493yJVMw8teCu9JxapxMFPFzI0hNUqdo0Y2nGW4kckk,6200
206
208
  verifiers/v1/utils/trace_store.py,sha256=Qo9qvsJAl8PoRUavjQAfUB2VNxmUtYQtU2ejLKPzY9c,3382
207
209
  verifiers/v1/utils/version.py,sha256=-obEo_-l9-D8FLef4hYxncOe-uJpxrM1g2Hig_37Sgs,1607
208
- verifiers-0.4.1.dev79.dist-info/METADATA,sha256=fS5SJdM1BzP7e4vK5aIRqqHoKTMpeNgjzfTLImABk40,5234
209
- verifiers-0.4.1.dev79.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
210
- verifiers-0.4.1.dev79.dist-info/entry_points.txt,sha256=O1bIO0gyJWuLfWtTGF0h-JkNz6FkyXP7Z9iMFYnjeMI,222
211
- verifiers-0.4.1.dev79.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
212
- verifiers-0.4.1.dev79.dist-info/RECORD,,
210
+ verifiers-0.4.1.dev80.dist-info/METADATA,sha256=mnfV3X0CeBJIqvI0Ld_Z_W6FYxaX8d0p9PhfwOSHyUA,5234
211
+ verifiers-0.4.1.dev80.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
212
+ verifiers-0.4.1.dev80.dist-info/entry_points.txt,sha256=O1bIO0gyJWuLfWtTGF0h-JkNz6FkyXP7Z9iMFYnjeMI,222
213
+ verifiers-0.4.1.dev80.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
214
+ verifiers-0.4.1.dev80.dist-info/RECORD,,