verifiers 0.4.1.dev96__py3-none-any.whl → 0.4.1.dev98__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.
@@ -6,7 +6,6 @@ The judge has its own non-training trace and writes rubric verdicts to a file.
6
6
  """
7
7
 
8
8
  import copy
9
- import json
10
9
  import re
11
10
  from pathlib import Path
12
11
 
@@ -28,6 +27,9 @@ from verifiers.v1.utils.compile import validate_pairing
28
27
 
29
28
  VERDICT_FILE = "/tmp/verdict.json"
30
29
  TRACE_FILE = "/tmp/trace.json"
30
+ HIDDEN_REASONING = {"reasoning_content", "provider_state"}
31
+ """Message fields a judge's trace file leaves out by default: hidden reasoning and
32
+ provider-only state."""
31
33
 
32
34
  GRADE_PROMPT = """\
33
35
  You are grading another agent's attempt at a task. Verify the work EMPIRICALLY:
@@ -138,16 +140,12 @@ class JudgeTask(vf.Task):
138
140
  ) -> "JudgeTask":
139
141
  """Build the verdict task for the already prepared scoring workspace."""
140
142
  solved = solution.task.data
141
- record = solution.to_record()
142
143
  # This snapshot is evidence for verification, not its final outcome.
143
144
  # stop() marks the agent loop completed before rollout scoring finishes.
144
- record.pop("ok", None)
145
+ exclude: dict = {"ok": True}
145
146
  if not config.include_hidden_reasoning:
146
- for node in record["nodes"]:
147
- message = node["message"]
148
- message.pop("reasoning_content", None)
149
- message.pop("provider_state", None)
150
- files = {TRACE_FILE: json.dumps(record).encode()}
147
+ exclude["nodes"] = {"__all__": {"message": HIDDEN_REASONING}}
148
+ files = {TRACE_FILE: solution.to_json(exclude=exclude)}
151
149
  template = config.build_prompt()
152
150
  body = _render(template, prompt=solved.prompt_text)
153
151
  if "{prompt}" not in template:
@@ -9,7 +9,6 @@ score averaged across them.
9
9
  """
10
10
 
11
11
  import asyncio
12
- import json
13
12
  import random
14
13
  import shlex
15
14
  import statistics
@@ -19,6 +18,7 @@ from pydantic import BaseModel, ConfigDict, Field
19
18
 
20
19
  import verifiers.v1 as vf
21
20
  from verifiers.v1.envs.agentic_judge.env import (
21
+ HIDDEN_REASONING,
22
22
  VERDICT_FILE,
23
23
  JudgeTaskConfig,
24
24
  ScoreConfig,
@@ -130,13 +130,10 @@ class RankTask(vf.Task):
130
130
 
131
131
  @staticmethod
132
132
  def record(attempt: vf.Trace) -> bytes:
133
- record = attempt.to_record()
134
133
  # 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()
134
+ return attempt.to_json(
135
+ exclude={"ok": True, "nodes": {"__all__": {"message": HIDDEN_REASONING}}}
136
+ )
140
137
 
141
138
  async def setup(self, trace: vf.Trace, runtime: vf.Runtime) -> None:
142
139
  # Archive bytes are the attempts': confine every member to its declared
verifiers/v1/episode.py CHANGED
@@ -3,13 +3,22 @@
3
3
  import uuid
4
4
  from typing import Annotated, Any, Generic, Literal, Self
5
5
 
6
+ import orjson
6
7
  from pydantic import BaseModel, Field, computed_field, model_validator
7
8
 
8
9
  from verifiers.v1.configs.agent import WireAgentConfig
9
10
  from verifiers.v1.graph import RECORD_FLOAT_DECIMALS
10
11
  from verifiers.v1.state import State, StateT
11
12
  from verifiers.v1.task import DataT, WireTaskData
12
- from verifiers.v1.trace import EXCLUDE_FIELDS, AgentConfigT, Error, Trace, TraceTask
13
+ from verifiers.v1.trace import (
14
+ RECORD_DUMP_EXCLUDE,
15
+ AgentConfigT,
16
+ Error,
17
+ Trace,
18
+ TraceTask,
19
+ add_record_streams,
20
+ merge_exclude,
21
+ )
13
22
  from verifiers.v1.types import Usage
14
23
 
15
24
 
@@ -154,15 +163,34 @@ class Episode(BaseModel, Generic[DataT, StateT, AgentConfigT]):
154
163
  return grouped
155
164
 
156
165
  def to_record(
157
- self, float_decimals: int | None = RECORD_FLOAT_DECIMALS
166
+ self,
167
+ float_decimals: int | None = RECORD_FLOAT_DECIMALS,
168
+ exclude: dict | set | None = None,
158
169
  ) -> dict[str, Any]:
159
170
  """JSON record without raw trace tensors, which remain on the msgpack wire.
160
- Per-token float streams are rounded to `float_decimals` (`None` keeps every digit)."""
161
- return self.model_dump(
171
+ Per-token node streams are numpy arrays (`graph.RECORD_STREAMS`): encode it with
172
+ `to_json`, or with orjson and `OPT_SERIALIZE_NUMPY`. Per-token float streams are
173
+ rounded to `float_decimals` (`None` keeps every digit). `exclude` is a pydantic
174
+ exclude spec for the other fields; the streams are always included."""
175
+ record = self.model_dump(
162
176
  mode="json",
163
- exclude={"traces": {"__all__": EXCLUDE_FIELDS}},
177
+ exclude=merge_exclude(
178
+ {"traces": {"__all__": RECORD_DUMP_EXCLUDE}}, exclude
179
+ ),
164
180
  exclude_none=True,
165
- context={"float_decimals": float_decimals},
181
+ )
182
+ for trace_record, trace in zip(record["traces"], self.traces, strict=True):
183
+ add_record_streams(trace_record, trace, float_decimals, exclude_none=True)
184
+ return record
185
+
186
+ def to_json(
187
+ self,
188
+ float_decimals: int | None = RECORD_FLOAT_DECIMALS,
189
+ exclude: dict | set | None = None,
190
+ ) -> bytes:
191
+ """`to_record` as compact UTF-8 JSON. NaN and infinity become `null`."""
192
+ return orjson.dumps(
193
+ self.to_record(float_decimals, exclude), option=orjson.OPT_SERIALIZE_NUMPY
166
194
  )
167
195
 
168
196
 
verifiers/v1/graph.py CHANGED
@@ -88,19 +88,40 @@ ROUNDED_STREAMS = (
88
88
  """Float streams a JSON record rounds to `float_decimals`. Loss weights stay exact: a 1/T
89
89
  weight would round to zero."""
90
90
 
91
+ RECORD_STREAMS = ("token_ids", "mask", "is_content", *ROUNDED_STREAMS, "loss_weights")
92
+ """Per-token node fields a JSON record (`to_record`) carries as numpy arrays — `loss_weights`
93
+ as a dict of them — so an encoder writes each stream in one pass instead of element by
94
+ element."""
95
+
96
+
97
+ def round_stream(values: list | np.ndarray, decimals: int) -> np.ndarray:
98
+ """A float stream rounded to `decimals`, in float64."""
99
+ return np.round(np.asarray(values, dtype=np.float64), decimals)
100
+
101
+
102
+ def _record_array(values: list | np.ndarray, decimals: int | None) -> np.ndarray:
103
+ """A stream as a record array: C-contiguous, which numpy-aware encoders require. Floats
104
+ widen to float64 so they print the digits a list of Python floats does — float32 would
105
+ print its own shortest form."""
106
+ array = np.asarray(values)
107
+ if array.dtype.kind == "f":
108
+ if decimals is not None:
109
+ return round_stream(array, decimals)
110
+ return array.astype(np.float64)
111
+ return np.ascontiguousarray(array)
112
+
91
113
 
92
114
  def _serialize_stream(
93
115
  values: list | np.ndarray, info: FieldSerializationInfo, rounded: bool
94
116
  ) -> list | dict:
95
- """JSON records: a list. Python dumps: a list too, unless the context sets `token_arrays`,
117
+ """JSON dumps: a list. Python dumps: a list too, unless the context sets `token_arrays`,
96
118
  when the msgpack wire carries a raw-bytes `__nd__` dict."""
97
119
  context = info.context or {}
98
120
  if info.mode_is_json():
99
- values = as_list(values)
100
121
  decimals = context.get("float_decimals", RECORD_FLOAT_DECIMALS)
101
122
  if not rounded or decimals is None:
102
- return values
103
- return [round(value, decimals) for value in values]
123
+ return as_list(values)
124
+ return round_stream(values, decimals).tolist()
104
125
  if context.get("token_arrays"):
105
126
  return encode_ndarray(np.asarray(values))
106
127
  return as_list(values)
@@ -207,6 +228,26 @@ class MessageNode(BaseModel):
207
228
  else self.renderer_token_ids
208
229
  )
209
230
 
231
+ def record_streams(
232
+ self, float_decimals: int | None, exclude_none: bool
233
+ ) -> dict[str, Any]:
234
+ """This node's `RECORD_STREAMS` for its JSON record, as numpy arrays. Float streams
235
+ in `ROUNDED_STREAMS` are rounded to `float_decimals` (`None` keeps every digit)."""
236
+ streams: dict[str, Any] = {}
237
+ for name in RECORD_STREAMS:
238
+ values = getattr(self, name)
239
+ if values is None:
240
+ if not exclude_none:
241
+ streams[name] = None
242
+ elif name == "loss_weights":
243
+ streams[name] = {
244
+ key: _record_array(stream, None) for key, stream in values.items()
245
+ }
246
+ else:
247
+ decimals = float_decimals if name in ROUNDED_STREAMS else None
248
+ streams[name] = _record_array(values, decimals)
249
+ return streams
250
+
210
251
  @field_serializer("token_ids", "mask", "is_content", *ROUNDED_STREAMS)
211
252
  def serialize_token_stream(
212
253
  self, values: list | np.ndarray | None, info: FieldSerializationInfo
@@ -1,7 +1,7 @@
1
1
  from verifiers.v1.serve.client import EnvClient
2
2
  from verifiers.v1.serve.delta import EpisodeAssembly
3
3
  from verifiers.v1.serve.pool import EnvServerPool, env_config_data, serve_env
4
- from verifiers.v1.serve.server import EnvServer
4
+ from verifiers.v1.serve.server import EnvServer, set_episode_hook
5
5
  from verifiers.v1.serve.types import (
6
6
  HealthRequest,
7
7
  HealthResponse,
@@ -20,4 +20,5 @@ __all__ = [
20
20
  "RunResponse",
21
21
  "env_config_data",
22
22
  "serve_env",
23
+ "set_episode_hook",
23
24
  ]
@@ -169,12 +169,13 @@ class EnvClient:
169
169
  response_type: type[ResponseT],
170
170
  timeout: float | None = None,
171
171
  on_delta: Callable[[dict], None] | None = None,
172
+ request_id: str | None = None,
172
173
  ) -> ResponseT:
173
174
  """Send a typed request and validate the reply into `response_type`. A
174
175
  `timeout` is only used for health polling — rollouts run untimed. `on_delta`
175
176
  receives each decoded `delta` the request streams before its reply."""
176
177
  self._ensure_receiver()
177
- request_id = uuid.uuid4().hex
178
+ request_id = request_id or uuid.uuid4().hex
178
179
  future: asyncio.Future[bytes] = asyncio.get_running_loop().create_future()
179
180
  self._pending[request_id] = future
180
181
  if on_delta is not None:
@@ -191,14 +192,7 @@ class EnvClient:
191
192
  except asyncio.CancelledError:
192
193
  self._pending.pop(request_id, None)
193
194
  if request.method == RunRequest.method:
194
- # Fire-and-forget: tell the server to abort the rollout so the
195
- # episode stops consuming inference and env-runtime resources.
196
- # A task on the loop outlives this (cancelled) caller.
197
- task = asyncio.get_running_loop().create_task(
198
- self._send_cancel(request_id)
199
- )
200
- self._cancel_tasks.add(task)
201
- task.add_done_callback(self._cancel_tasks.discard)
195
+ self._cancel_run(request_id)
202
196
  raise
203
197
  finally:
204
198
  self._deltas.pop(request_id, None)
@@ -223,6 +217,14 @@ class EnvClient:
223
217
  )
224
218
  raise
225
219
 
220
+ def _cancel_run(self, run_request_id: str) -> None:
221
+ """Fire-and-forget: tell the server the caller abandoned the run, so it aborts
222
+ the rollout (or frees what it kept for an episode already sent). A task on the
223
+ loop outlives the cancelled caller."""
224
+ task = asyncio.get_running_loop().create_task(self._send_cancel(run_request_id))
225
+ self._cancel_tasks.add(task)
226
+ task.add_done_callback(self._cancel_tasks.discard)
227
+
226
228
  async def _send_cancel(self, run_request_id: str) -> None:
227
229
  """Best-effort server-side abort of an abandoned run."""
228
230
  with contextlib.suppress(Exception):
@@ -276,6 +278,7 @@ class EnvClient:
276
278
  if on_delta is not None:
277
279
  on_delta(delta)
278
280
 
281
+ request_id = uuid.uuid4().hex
279
282
  response = await self._request(
280
283
  RunRequest(
281
284
  task_data=task_data,
@@ -285,11 +288,19 @@ class EnvClient:
285
288
  ),
286
289
  RunResponse,
287
290
  on_delta=apply,
291
+ request_id=request_id,
288
292
  )
289
293
  assert response.head is not None
290
- return await self._decode(
291
- WireEpisode.model_validate, assembly.finish(response.head, response.traces)
292
- )
294
+ try:
295
+ return await self._decode(
296
+ WireEpisode.model_validate,
297
+ assembly.finish(response.head, response.traces),
298
+ )
299
+ except BaseException:
300
+ # The reply already arrived, so the server counts the episode delivered;
301
+ # tell it this caller never got the episode.
302
+ self._cancel_run(request_id)
303
+ raise
293
304
 
294
305
  async def close(self) -> None:
295
306
  if self._receiver is not None:
@@ -4,12 +4,13 @@ The worker streams a served episode as it grows. Each trace announces its own ch
4
4
  (`Trace.notify`, fired by the rollout at every phase change and by the interception proxy
5
5
  after every recorded turn); the `DeltaStreamer` then diffs the run's live traces against
6
6
  what it has already sent and ships only the new part — the trace header once, then
7
- appended nodes / calls / errors, semantic links and routing-row repairs on earlier nodes, the scalar
7
+ appended nodes / calls / errors, semantic links on earlier nodes, the scalar
8
8
  fields whose value changed (timing spans, stop condition, rewards, ...), and the
9
9
  `pending` preview — the messages of the request in flight that no node holds yet, so a
10
10
  watcher sees a tool result before the model has answered it. The `Trace` is
11
- append-only at turn granularity except for links and the last routing row of a node,
12
- which the next prefill can repair. Apart from these and the preview, every byte of the
11
+ append-only at turn granularity except for links. Nodes stream without their per-token
12
+ training arrays (`TRAINING_ARRAY_FIELDS`): a host that trains on them keeps them itself
13
+ (`set_episode_hook`). Apart from links and the preview, every byte of the
13
14
  episode crosses the wire once and the stream costs about what a single reply would; the
14
15
  reply that ends the run carries only the episode head and per-trace counts the client
15
16
  checks its assembly against. A cursor advances only once its delta is on the wire, so a
@@ -29,10 +30,8 @@ from collections.abc import Awaitable, Callable, Iterable
29
30
  from typing import TYPE_CHECKING, Any, Self
30
31
 
31
32
  import msgpack
32
- import numpy as np
33
33
  from pydantic import BaseModel
34
34
 
35
- from verifiers.v1.graph import decode_ndarray, encode_ndarray
36
35
  from verifiers.v1.serve.encoding import msgpack_encoder
37
36
 
38
37
  if TYPE_CHECKING:
@@ -74,6 +73,10 @@ SCALAR_FIELDS = (
74
73
  """Re-sent whole whenever their dumped value changes."""
75
74
 
76
75
 
76
+ TRAINING_ARRAY_FIELDS = frozenset({"routed_experts", "sampling_mask", "top_logprobs"})
77
+ """Node fields holding per-token training arrays; never streamed."""
78
+
79
+
77
80
  def pack(payload: Any) -> bytes:
78
81
  return msgpack.packb(payload, default=msgpack_encoder, use_bin_type=True)
79
82
 
@@ -96,8 +99,6 @@ class TraceCursor:
96
99
  self.sent = dict.fromkeys(LIST_FIELDS, 0)
97
100
  self.links: list[int] = []
98
101
  """Per sent node, how many of its semantic links went out with or after it."""
99
- self.final_rows: dict[int, bytes] = {}
100
- """Per node that carries routing, its final row as packed when last sent."""
101
102
  self.scalars: dict[str, bytes] = {}
102
103
  self.pending: bytes = pack([])
103
104
 
@@ -169,31 +170,6 @@ class DeltaStreamer:
169
170
  else:
170
171
  self.cursors[trace_id] = cursor
171
172
 
172
- def _maybe_add_routing_repairs(
173
- self,
174
- delta: dict[str, Any],
175
- trace: Trace,
176
- cursor: TraceCursor,
177
- sent_nodes: int,
178
- ) -> None:
179
- """Add final rows repaired since they were sent, keyed by node index.
180
-
181
- Record every node's current row on the cursor. `sent_nodes` is the pre-flush
182
- count, so a node first sent in this delta is never reported as a repair.
183
- """
184
- repairs: dict[int, dict] = {}
185
- for index, node in enumerate(trace.nodes):
186
- if node.routed_experts is None:
187
- continue
188
- row = encode_ndarray(node.routed_experts[-1:])
189
- packed = pack(row)
190
- if cursor.final_rows.get(index) != packed:
191
- cursor.final_rows[index] = packed
192
- if index < sent_nodes:
193
- repairs[index] = row
194
- if repairs:
195
- delta["routing_repairs"] = repairs
196
-
197
173
  def diff(self) -> list[tuple[str, dict, TraceCursor | None]]:
198
174
  """Each trace's delta against its sent cursor, with the cursor as it stands once
199
175
  that delta is sent (None for a discard). Nothing here is committed: `flush`
@@ -220,15 +196,19 @@ class DeltaStreamer:
220
196
  cursor.links[index] = len(node_links)
221
197
  if links:
222
198
  delta["links"] = links
223
- self._maybe_add_routing_repairs(delta, trace, cursor, cursor.sent["nodes"])
224
199
  for field in LIST_FIELDS:
225
200
  items = getattr(trace, field)
226
201
  sent = cursor.sent[field]
227
202
  if len(items) > sent:
228
203
  # Nodes' per-token streams ride as raw-bytes arrays.
229
- context = {"token_arrays": True} if field == "nodes" else None
204
+ is_nodes = field == "nodes"
230
205
  delta[field] = [
231
- dump(item, context=context) for item in items[sent:]
206
+ dump(
207
+ item,
208
+ context={"token_arrays": True} if is_nodes else None,
209
+ exclude=TRAINING_ARRAY_FIELDS if is_nodes else None,
210
+ )
211
+ for item in items[sent:]
232
212
  ]
233
213
  cursor.sent[field] = len(items)
234
214
  if field == "nodes":
@@ -262,20 +242,6 @@ class EpisodeAssembly:
262
242
  def __init__(self) -> None:
263
243
  self.traces: dict[str, dict] = {}
264
244
 
265
- def _maybe_apply_routing_repairs(self, delta: dict[str, Any], trace: dict) -> None:
266
- """Replace repaired final rows in nodes the client already holds.
267
-
268
- Rebuild each array: a repair can widen its dtype, and decoded rows alias
269
- the original delta's bytes, which must remain unchanged for consumers.
270
- """
271
- for index, row in (delta.get("routing_repairs") or {}).items():
272
- node = trace["nodes"][int(index)]
273
- node["routed_experts"] = encode_ndarray(
274
- np.concatenate(
275
- [decode_ndarray(node["routed_experts"])[:-1], decode_ndarray(row)]
276
- )
277
- )
278
-
279
245
  def apply(self, delta: dict) -> None:
280
246
  trace_id = delta["trace"]
281
247
  if delta.get("discard"):
@@ -290,7 +256,6 @@ class EpisodeAssembly:
290
256
  }
291
257
  for index, links in (delta.get("links") or {}).items():
292
258
  trace["nodes"][int(index)]["semantic_parents"].extend(links)
293
- self._maybe_apply_routing_repairs(delta, trace)
294
259
  # a later `links` delta grows a node's semantic_parents in place, so the node
295
260
  # is copied: the delta stays as it was when the caller received it
296
261
  if "nodes" in delta:
@@ -28,6 +28,7 @@ import os
28
28
  import signal
29
29
  import tempfile
30
30
  import threading
31
+ import time
31
32
  from collections.abc import Callable
32
33
 
33
34
  import msgpack
@@ -35,7 +36,7 @@ import zmq
35
36
  import zmq.asyncio
36
37
 
37
38
  from verifiers.v1.configs.env import EnvConfig
38
- from verifiers.v1.serve.server import EnvServer
39
+ from verifiers.v1.serve.server import LATE_CANCEL_SECONDS, EnvServer
39
40
  from verifiers.v1.serve.types import CancelResponse, HealthResponse
40
41
 
41
42
  logger = logging.getLogger(__name__)
@@ -172,6 +173,9 @@ class EnvServerPool:
172
173
  self._spawn_worker()
173
174
  # request_id -> {client_id, worker}
174
175
  pending: dict[bytes, dict] = {}
176
+ # request_id -> (replied_at, worker), oldest first: a late cancel still reaches
177
+ # the worker that may hold the run's kept arrays (`LATE_CANCEL_SECONDS`).
178
+ replied: dict[bytes, tuple[float, dict]] = {}
175
179
  logger.info(
176
180
  "EnvServerPool up: address=%s workers=%d/%s multiplex=%d elastic=%s",
177
181
  self.address,
@@ -199,8 +203,10 @@ class EnvServerPool:
199
203
  [client_id, request_id, b"reply", _HEALTH]
200
204
  )
201
205
  elif method == b"cancel":
202
- # Route the cancel to the worker holding the target run;
203
- # an unknown/finished target (or an unparseable payload
206
+ # Route the cancel to the worker holding the target run,
207
+ # or to the one that replied to it within
208
+ # `LATE_CANCEL_SECONDS` (it may hold the run's kept
209
+ # arrays); any other target (or an unparseable payload
204
210
  # — one bad frame must not tear down the broker) is
205
211
  # answered inline
206
212
  try:
@@ -209,12 +215,21 @@ class EnvServerPool:
209
215
  except Exception: # noqa: BLE001 - one bad frame must not kill the broker
210
216
  target = b""
211
217
  target_entry = pending.get(target)
212
- if target_entry is None:
218
+ late = replied.get(target)
219
+ if target_entry is not None:
220
+ worker = target_entry["worker"]
221
+ elif (
222
+ late is not None
223
+ and time.monotonic() - late[0] < LATE_CANCEL_SECONDS
224
+ ):
225
+ worker = late[1]
226
+ else:
227
+ worker = None
228
+ if worker is None:
213
229
  await self.frontend.send_multipart(
214
230
  [client_id, request_id, b"reply", _CANCEL_MISS]
215
231
  )
216
232
  else:
217
- worker = target_entry["worker"]
218
233
  worker["active"] += 1
219
234
  pending[request_id] = {
220
235
  "client_id": client_id,
@@ -253,6 +268,12 @@ class EnvServerPool:
253
268
  continue
254
269
  entry["worker"]["active"] -= 1
255
270
  in_flight -= 1
271
+ now = time.monotonic()
272
+ replied[request_id.bytes] = (now, entry["worker"])
273
+ for old, (replied_at, _) in list(replied.items()):
274
+ if now - replied_at < LATE_CANCEL_SECONDS:
275
+ break
276
+ del replied[old]
256
277
  else:
257
278
  entry = pending.get(request_id.bytes)
258
279
  if entry is None:
@@ -1,5 +1,8 @@
1
1
  import asyncio
2
2
  import logging
3
+ import threading
4
+ import time
5
+ from typing import Protocol
3
6
 
4
7
  import msgpack
5
8
  import zmq
@@ -9,6 +12,7 @@ from verifiers.v1.clients import ModelContext
9
12
  from verifiers.v1.configs.client import ClientConfig
10
13
  from verifiers.v1.configs.env import EnvConfig
11
14
  from verifiers.v1.configs.sampling import SamplingConfig
15
+ from verifiers.v1.episode import Episode
12
16
  from verifiers.v1.serve.delta import DeltaStreamer, TraceSummary, dump, pack
13
17
  from verifiers.v1.serve.encoding import msgpack_encoder
14
18
  from verifiers.v1.serve.types import (
@@ -25,6 +29,66 @@ from verifiers.v1.utils.loaders import load_environment
25
29
  logger = logging.getLogger(__name__)
26
30
 
27
31
 
32
+ class EpisodeHook(Protocol):
33
+ """Takes finished episodes' per-token training arrays (routing rows, sampling masks,
34
+ top-k heads) before the episodes leave the worker."""
35
+
36
+ def keep(self, episode: Episode, sampling: SamplingConfig) -> None:
37
+ """Keep the episode's arrays; may leave references to them in `trace.info`.
38
+ Runs off the event loop, before the episode's final flush."""
39
+
40
+ def discard(self, episode: Episode) -> None:
41
+ """Free what `keep` kept for an episode that was not delivered."""
42
+
43
+
44
+ _episode_hook: EpisodeHook | None = None
45
+
46
+ LATE_CANCEL_SECONDS = 10.0
47
+ """How long a delivered episode stays discardable: a client whose caller cancels the run
48
+ after the reply left drops the reply and sends a cancel right away."""
49
+
50
+
51
+ def set_episode_hook(hook: EpisodeHook | None) -> None:
52
+ """Install a hook that keeps finished episodes' training arrays. Streamed nodes never
53
+ carry them, so the hook is the only way they leave the worker. Every episode it
54
+ keeps is either delivered in its run's reply or handed back to `discard`, and so is
55
+ a delivered one whose client cancels the run within `LATE_CANCEL_SECONDS`."""
56
+ global _episode_hook
57
+ _episode_hook = hook
58
+
59
+
60
+ class _Keeping:
61
+ """One episode's `keep`, run off the event loop. A failed or abandoned `keep` hands
62
+ the episode to `discard` exactly once, and only after `keep` has returned: in the
63
+ thread when `keep` finishes last, else in `abandon`."""
64
+
65
+ def __init__(self, hook: EpisodeHook, episode: Episode) -> None:
66
+ self.hook = hook
67
+ self.episode = episode
68
+ self._lock = threading.Lock()
69
+ self._kept = False
70
+ self._abandoned = False
71
+
72
+ def run(self, sampling: SamplingConfig) -> None:
73
+ try:
74
+ self.hook.keep(self.episode, sampling)
75
+ except BaseException:
76
+ self.hook.discard(self.episode)
77
+ raise
78
+ with self._lock:
79
+ self._kept = True
80
+ discard = self._abandoned
81
+ if discard:
82
+ self.hook.discard(self.episode)
83
+
84
+ def abandon(self) -> None:
85
+ with self._lock:
86
+ self._abandoned = True
87
+ discard = self._kept
88
+ if discard:
89
+ self.hook.discard(self.episode)
90
+
91
+
28
92
  class EnvServer:
29
93
  def __init__(
30
94
  self,
@@ -52,6 +116,10 @@ class EnvServer:
52
116
  self._gate = asyncio.Semaphore(max_concurrent) if max_concurrent else None
53
117
  # In-flight run tasks by wire request_id, so a `cancel` can abort them
54
118
  self._running: dict[str, asyncio.Task] = {}
119
+ # Episodes the hook kept, by run request, until their reply is sent.
120
+ self._kept: dict[bytes, tuple[EpisodeHook, Episode]] = {}
121
+ self._delivered: dict[str, tuple[float, EpisodeHook, Episode]] = {}
122
+ """Recently delivered kept episodes, oldest first, for a cancel that arrives late."""
55
123
  self.ctx = zmq.asyncio.Context()
56
124
  self.frontend = self.ctx.socket(zmq.ROUTER)
57
125
  self.frontend.setsockopt(zmq.ROUTER_MANDATORY, 1)
@@ -108,10 +176,21 @@ class EnvServer:
108
176
  # The gate spans requests: `--max-concurrent` bounds this worker's episodes
109
177
  # in flight the same way the in-process eval's semaphore does. The streamer
110
178
  # ships each trace as it changes; the reply below carries only the rest.
179
+ hook = _episode_hook
111
180
  async with DeltaStreamer(lambda: slot.traces, send_delta) as streamer:
112
181
  episode = await self.env.run_slot(
113
182
  slot, ctx, self._gate, on_trace=streamer.watch
114
183
  )
184
+ if hook is not None:
185
+ # Before the final flush, so what the hook writes to the traces streams.
186
+ keeping = _Keeping(hook, episode)
187
+ try:
188
+ # The thread runs to the end even when this await is cancelled.
189
+ await asyncio.shield(asyncio.to_thread(keeping.run, ctx.sampling))
190
+ except asyncio.CancelledError:
191
+ keeping.abandon()
192
+ raise
193
+ self._kept[request_id] = (hook, episode)
115
194
  return RunResponse(
116
195
  head=dump(episode, exclude={"traces"}),
117
196
  traces=[
@@ -144,6 +223,14 @@ class EnvServer:
144
223
  if running is not None:
145
224
  running.cancel()
146
225
  logger.info("cancelled run %s on client request", target)
226
+ # The client dropped the reply, or will: nothing will take the arrays.
227
+ self._expire_delivered()
228
+ kept = self._kept.pop(target.encode(), None)
229
+ if kept is None and (late := self._delivered.pop(target, None)):
230
+ kept = late[1:]
231
+ if kept is not None:
232
+ hook, episode = kept
233
+ hook.discard(episode)
147
234
  response = CancelResponse(cancelled=running is not None)
148
235
  else:
149
236
  response = BaseResponse(
@@ -167,18 +254,40 @@ class EnvServer:
167
254
  except Exception as e:
168
255
  # Encoding failures must also reply so clients don't wait indefinitely.
169
256
  logger.warning("response encoding failed: %s", e, exc_info=True)
170
- data = msgpack.packb(
171
- BaseResponse(
172
- success=False, error=f"{type(e).__name__}: {e}"
173
- ).model_dump(),
174
- use_bin_type=True,
175
- )
257
+ response = BaseResponse(success=False, error=f"{type(e).__name__}: {e}")
258
+ data = msgpack.packb(response.model_dump(), use_bin_type=True)
259
+ delivered = False
176
260
  try:
177
261
  await self.frontend.send_multipart(
178
262
  [client_id, request_id, b"reply", data], copy=False
179
263
  )
264
+ delivered = response.success
180
265
  except zmq.ZMQError as e:
181
266
  logger.warning("failed to send response: %s", e)
267
+ finally:
268
+ # Also on a cancel (shutdown) while the reply is sending.
269
+ kept = self._kept.pop(request_id, None)
270
+ if kept is not None:
271
+ hook, episode = kept
272
+ if delivered:
273
+ self._remember_delivered(request_id.decode(), hook, episode)
274
+ else:
275
+ hook.discard(episode)
276
+
277
+ def _remember_delivered(
278
+ self, request_id: str, hook: EpisodeHook, episode: Episode
279
+ ) -> None:
280
+ self._delivered[request_id] = (time.monotonic(), hook, episode)
281
+ asyncio.get_running_loop().call_later(
282
+ LATE_CANCEL_SECONDS, self._expire_delivered
283
+ )
284
+
285
+ def _expire_delivered(self) -> None:
286
+ now = time.monotonic()
287
+ for request_id, (delivered_at, _, _) in list(self._delivered.items()):
288
+ if now - delivered_at < LATE_CANCEL_SECONDS:
289
+ break
290
+ del self._delivered[request_id]
182
291
 
183
292
  async def run(self) -> None:
184
293
  logger.info(
verifiers/v1/trace.py CHANGED
@@ -9,6 +9,7 @@ from collections.abc import Callable, Iterable, Iterator, Mapping
9
9
  from typing import TYPE_CHECKING, Any, Generic
10
10
 
11
11
  import numpy as np
12
+ import orjson
12
13
  from pydantic import BaseModel, Field, PrivateAttr, computed_field, field_serializer
13
14
  from typing_extensions import TypeVar
14
15
 
@@ -52,6 +53,42 @@ EXCLUDE_FIELDS: dict = {
52
53
  }
53
54
  """Raw tensor fields kept on the msgpack wire but excluded from disk serialization."""
54
55
 
56
+ RECORD_DUMP_EXCLUDE: dict = {
57
+ "nodes": {"__all__": EXCLUDE_FIELDS["nodes"]["__all__"] | set(graph.RECORD_STREAMS)}
58
+ }
59
+ """What `to_record` leaves out of its pydantic dump: the wire-only tensors, and the per-token
60
+ streams, which `add_record_streams` adds as numpy arrays. Pydantic's JSON mode cannot emit
61
+ numpy arrays, and building the streams as lists of Python numbers would be most of the cost
62
+ of a record."""
63
+
64
+
65
+ def merge_exclude(*excludes: dict | set | None) -> dict:
66
+ """Pydantic `exclude` specs combined into one. A field that any spec excludes whole
67
+ stays excluded whole."""
68
+ merged: dict = {}
69
+ for exclude in excludes:
70
+ if not exclude:
71
+ continue
72
+ items = dict.fromkeys(exclude, True) if isinstance(exclude, set) else exclude
73
+ for key, value in items.items():
74
+ current = merged.get(key)
75
+ if current is True or value is True or value is ...:
76
+ merged[key] = True
77
+ else:
78
+ merged[key] = merge_exclude(current, value)
79
+ return merged
80
+
81
+
82
+ def add_record_streams(
83
+ record: dict[str, Any],
84
+ trace: Trace,
85
+ float_decimals: int | None,
86
+ exclude_none: bool,
87
+ ) -> None:
88
+ """Join a trace's record (dumped with `RECORD_DUMP_EXCLUDE`) with its node streams."""
89
+ for node_record, node in zip(record["nodes"], trace.nodes, strict=True):
90
+ node_record.update(node.record_streams(float_decimals, exclude_none))
91
+
55
92
 
56
93
  class TimeSpan(BaseModel):
57
94
  """Wall-clock timestamps with a derived, non-serialized duration in seconds."""
@@ -796,14 +833,29 @@ class Trace(BaseModel, Generic[DataT, StateT, AgentConfigT]):
796
833
  self.stop(stop_condition(error))
797
834
 
798
835
  def to_record(
799
- self, float_decimals: int | None = RECORD_FLOAT_DECIMALS
836
+ self,
837
+ float_decimals: int | None = RECORD_FLOAT_DECIMALS,
838
+ exclude: dict | set | None = None,
800
839
  ) -> dict[str, Any]:
801
840
  """JSON record without raw tensors, which remain available on the msgpack wire.
802
- Per-token float streams are rounded to `float_decimals` (`None` keeps every digit)."""
803
- return self.model_dump(
804
- mode="json",
805
- exclude=EXCLUDE_FIELDS,
806
- context={"float_decimals": float_decimals},
841
+ Per-token node streams are numpy arrays (`graph.RECORD_STREAMS`): encode it with
842
+ `to_json`, or with orjson and `OPT_SERIALIZE_NUMPY`. Per-token float streams are
843
+ rounded to `float_decimals` (`None` keeps every digit). `exclude` is a pydantic
844
+ exclude spec for the other fields; the streams are always included."""
845
+ record = self.model_dump(
846
+ mode="json", exclude=merge_exclude(RECORD_DUMP_EXCLUDE, exclude)
847
+ )
848
+ add_record_streams(record, self, float_decimals, exclude_none=False)
849
+ return record
850
+
851
+ def to_json(
852
+ self,
853
+ float_decimals: int | None = RECORD_FLOAT_DECIMALS,
854
+ exclude: dict | set | None = None,
855
+ ) -> bytes:
856
+ """`to_record` as compact UTF-8 JSON. NaN and infinity become `null`."""
857
+ return orjson.dumps(
858
+ self.to_record(float_decimals, exclude), option=orjson.OPT_SERIALIZE_NUMPY
807
859
  )
808
860
 
809
861
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: verifiers
3
- Version: 0.4.1.dev96
3
+ Version: 0.4.1.dev98
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
@@ -34,6 +34,7 @@ Requires-Dist: mcp==2.2.0
34
34
  Requires-Dist: msgpack>=1.1.2
35
35
  Requires-Dist: numpy>=2.1.0
36
36
  Requires-Dist: openai<3.0.0,>=2.54.0
37
+ Requires-Dist: orjson>=3.10.0
37
38
  Requires-Dist: prime-pydantic-config[toml]>=0.4.3
38
39
  Requires-Dist: prime-runs>=0.1.4
39
40
  Requires-Dist: prime-sandboxes>=0.5.1
@@ -2,10 +2,10 @@ verifiers/__init__.py,sha256=F5IVMw6mhGaPBMCw7QKk0la_r5mMwydP2hdTTdQucik,352
2
2
  verifiers/v1/__init__.py,sha256=2nz8TJC-CifIXzChXHaNVg0rUgYrerd1w6vysODI6Gk,18901
3
3
  verifiers/v1/agent.py,sha256=_PBWiO3dmAGQvD4rCb5SIW6nLvYd7BBsPf1qxsQIXPw,47290
4
4
  verifiers/v1/env.py,sha256=fxXBjVyi0milYViHt6O0vBK3JdM2TYSOoQpXd0P0rFE,18110
5
- verifiers/v1/episode.py,sha256=UPtA02aGWA-fY8cJKEuYCMtQVnPN1C0BSN13LggNT8U,5986
5
+ verifiers/v1/episode.py,sha256=gl6wXCTicFabjnEbJ1S7zI_Gg9jgRS9pJG68d45KJEY,6931
6
6
  verifiers/v1/errors.py,sha256=nNabzi55J5aHmAmW9UHZVpI7kcBfy4Xcyt4cQthZbM8,5875
7
7
  verifiers/v1/grading.py,sha256=Z8J9-UiQA_P8MOMn1CAGsD_SgmrQd6-H_VPmD27ezss,9685
8
- verifiers/v1/graph.py,sha256=ZLuaEl2SxIvMTgws5XNfy-SNjapylLuYtVbcLI2-rMU,46274
8
+ verifiers/v1/graph.py,sha256=FoywN6AGOJh6MlFUFW1vBjcQRh_-4YHckyAcXAW-oF0,48143
9
9
  verifiers/v1/harness.py,sha256=Hvul6cbb9uWQl4GmHubvcRHqKdfeCY3n44r_ga0csfI,16806
10
10
  verifiers/v1/judge.py,sha256=T-TyYVcLGIoyUADYKy_pCBj2CTLhERlct5pmmWqPpTA,10507
11
11
  verifiers/v1/rollout.py,sha256=Rrliwo9i-a-wcbE9rJZZTYA4vkDlNJBJNKecoldreBw,45907
@@ -14,7 +14,7 @@ verifiers/v1/session.py,sha256=Wp_IZyYGC2D35OokpYlJcSBUR_OS38QPYrhODOgnV3U,29371
14
14
  verifiers/v1/state.py,sha256=EckF2bWp-vV4b1jYJ9sLI5xrfGuI5spIgYYwW926toI,595
15
15
  verifiers/v1/task.py,sha256=rH9ekXd33LN7oynppiogZgY5L6s_DEbTyNPZ4GQEBss,15471
16
16
  verifiers/v1/taskset.py,sha256=LE_3ogL7itU2Amk-N20cHkZ7Ev6MznJ0HpC8B1xb4w0,9482
17
- verifiers/v1/trace.py,sha256=kXqoKL4vmmJkEPAw3rczqqPkHXHFLKKMCV9CYZ7LB6M,33061
17
+ verifiers/v1/trace.py,sha256=l22hxgq41TQ8jLfqqgAsrWCHCObhkymWZX3I3xs2t3U,35229
18
18
  verifiers/v1/types.py,sha256=wU81MAjdzy8FO3LUPjMQVRkEFMcVBUTtdHc068UDKJY,14804
19
19
  verifiers/v1/acp/__init__.py,sha256=jY7nLAbB6uzSl-f6YCz05zBH5tarBLErNTkvV0vlaho,16613
20
20
  verifiers/v1/acp/runner.py,sha256=sFsg0UgWeDjpjihejUidIV2yTapVj1Ap0cDTaEktjkI,15484
@@ -70,11 +70,11 @@ verifiers/v1/dialects/chat.py,sha256=KZJYJzrbb9Nhyqzp6fjOB1K5pzHX-CLaP4Yuh6zShOM
70
70
  verifiers/v1/dialects/responses.py,sha256=jd8-xZ65MOtnHnnH295s4TCUgvDbfyYg0ialKo3HvgE,31259
71
71
  verifiers/v1/envs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
72
72
  verifiers/v1/envs/agentic_judge/__init__.py,sha256=6vwtMCQ_cuvuubCF5-nrE5W7gGgzE-LIPKorkM5DXdw,309
73
- verifiers/v1/envs/agentic_judge/env.py,sha256=WLvEvM7bgTieCvOtmOLb-2RmWOwpMAd3m0GZuitUCzc,14956
73
+ verifiers/v1/envs/agentic_judge/env.py,sha256=AkANEM5mSiGJ-udJWvHKeNMVq4wRcWpXX0yOJ2qqS78,14968
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
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
77
+ verifiers/v1/envs/best_of_n_judge/env.py,sha256=GgHriH6qq4okzjKqYeFGU-1q5FKM3oZW6Cal4T2_u5M,14631
78
78
  verifiers/v1/envs/single_agent/__init__.py,sha256=r0edAc_6gtHBhPzeBGVcdHZZqSdCPZnLMje6eVgyz5U,138
79
79
  verifiers/v1/envs/single_agent/env.py,sha256=iH-AnS5-5rDZM3MaYFxzaHSVqJAaw9mQJaaJvsDMMX4,854
80
80
  verifiers/v1/envs/user_sim/__init__.py,sha256=nnT695HdqjAEouYL5wtVu6MhIp2wf5yuK-EYgxOVx0s,118
@@ -164,12 +164,12 @@ verifiers/v1/runtimes/backends/custom.py,sha256=Iz1Brd4dBTpO1zYVc2KA0u5sxz5ZUROY
164
164
  verifiers/v1/runtimes/backends/docker.py,sha256=k4I_LorHi-SpXjKwBoKUaxdrU8e3URPn7VNWGff3oyU,34099
165
165
  verifiers/v1/runtimes/backends/prime.py,sha256=KwsHQUDxecaRVDtEeSzTK8wKkf_-6nIwxmxJJ_1N9Zo,23862
166
166
  verifiers/v1/runtimes/backends/subprocess.py,sha256=dCfazoyJHwrfb2fMNRv6QzD6EsYlZXcEDT0x-8MAp3I,8419
167
- verifiers/v1/serve/__init__.py,sha256=wOKuwfugzmDT4yIniwzCXlf4G6tv6Cg8Kc--WMa38Bs,553
168
- verifiers/v1/serve/client.py,sha256=v-R17h3Tfcaw5395sf9ctXKW-HF_ldH_bvrW-FXrJ7E,13513
169
- verifiers/v1/serve/delta.py,sha256=hj6uFfUmUWrdIAqgWI7bj-yUlej-P1UEEWaXYqTgUk8,13861
167
+ verifiers/v1/serve/__init__.py,sha256=4Oe4xFVu-lyCHpG6u9e0TbmV7ZVYHiwFZXW8UO0H7mA,595
168
+ verifiers/v1/serve/client.py,sha256=el91rqoUpf_1Ty8-QVs_AV0MyNaQaQtxHYTLR2LwQHc,13948
169
+ verifiers/v1/serve/delta.py,sha256=f7irrdqaVqNNrFdhbrQ7-_OKj6fP16KekHtch1ikoPk,12317
170
170
  verifiers/v1/serve/encoding.py,sha256=hBZFucAZK9riXOV3DaHcskq9zHTT8gVGkoFVOPfnr30,2499
171
- verifiers/v1/serve/pool.py,sha256=pUvUhAvcTkLinFuTJJOp6pqi_sQdWsjJS4clLzgkRhc,16362
172
- verifiers/v1/serve/server.py,sha256=oVBGhxu-XF-b8atKesJvhF484Ne4G__DrcAr3DLAO68,9924
171
+ verifiers/v1/serve/pool.py,sha256=PQyP3-GLL9WFJbIe1L4IYCBOlOR0vTpwCctwrFuGgVo,17578
172
+ verifiers/v1/serve/server.py,sha256=KS1OiRMNRnhncQXlzwrdjh5g0-xT3Ov74aFdgJ1b1ZY,14536
173
173
  verifiers/v1/serve/types.py,sha256=Ua_dE4sC-APox-0Pnm-jgWcrLa9Qywafel32KrawY5I,1752
174
174
  verifiers/v1/tasksets/__init__.py,sha256=2ijE3qIlLoUA02g6iysOwWQylyBBQL1GhSpjv8_bp0w,521
175
175
  verifiers/v1/tasksets/harbor/__init__.py,sha256=FjW4tM3rgGALMK-8p7ux26G4-d4ZFVmaAmO6Fni6e_g,214
@@ -208,8 +208,8 @@ verifiers/v1/utils/scope.py,sha256=bzUEiWDOVdbj7dXOwGOlzsQ_-Xu0j9NR5TalQB-8TS8,8
208
208
  verifiers/v1/utils/score.py,sha256=493yJVMw8teCu9JxapxMFPFzI0hNUqdo0Y2nGW4kckk,6200
209
209
  verifiers/v1/utils/trace_store.py,sha256=Qo9qvsJAl8PoRUavjQAfUB2VNxmUtYQtU2ejLKPzY9c,3382
210
210
  verifiers/v1/utils/version.py,sha256=-obEo_-l9-D8FLef4hYxncOe-uJpxrM1g2Hig_37Sgs,1607
211
- verifiers-0.4.1.dev96.dist-info/METADATA,sha256=lxB0TswMVHRJ6RA9wd9oKvKxnpbwyUAIr1j7A8OXrl4,5234
212
- verifiers-0.4.1.dev96.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
213
- verifiers-0.4.1.dev96.dist-info/entry_points.txt,sha256=O1bIO0gyJWuLfWtTGF0h-JkNz6FkyXP7Z9iMFYnjeMI,222
214
- verifiers-0.4.1.dev96.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
215
- verifiers-0.4.1.dev96.dist-info/RECORD,,
211
+ verifiers-0.4.1.dev98.dist-info/METADATA,sha256=vjnLxJdJ4T3_v-AloF0_4IASfDCVey0YzjTpLmMTz_4,5264
212
+ verifiers-0.4.1.dev98.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
213
+ verifiers-0.4.1.dev98.dist-info/entry_points.txt,sha256=O1bIO0gyJWuLfWtTGF0h-JkNz6FkyXP7Z9iMFYnjeMI,222
214
+ verifiers-0.4.1.dev98.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
215
+ verifiers-0.4.1.dev98.dist-info/RECORD,,