verifiers 0.4.2.dev13__py3-none-any.whl → 0.4.2.dev18__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.
verifiers/v1/delta.py ADDED
@@ -0,0 +1,256 @@
1
+ """Incremental trace deltas, for anything that shows or records a trace while it runs.
2
+
3
+ A trace announces its own changes (`Trace.notify`, at every phase change and recorded turn).
4
+ `DeltaStreamer` diffs the watched traces against what it has already sent and hands `send` only
5
+ the new part: the header once, then appended nodes / calls / errors, semantic links added to
6
+ earlier nodes, scalar fields whose value changed, and the `pending` preview (messages of the
7
+ request in flight that no node holds yet). Nodes go without their per-token training arrays.
8
+ `EpisodeAssembly` applies those deltas back into raw trace dicts. The transport is the caller's:
9
+ a socket, a JSONL file, a queue. Both sides live here because the field lists track `Trace`.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import asyncio
15
+ import logging
16
+ from collections.abc import Awaitable, Callable, Iterable
17
+ from typing import Any, Self
18
+
19
+ from pydantic import BaseModel
20
+
21
+ from verifiers.v1.trace import Trace
22
+ from verifiers.v1.utils.logging import clip, get_logger
23
+
24
+ logger = get_logger(__name__)
25
+
26
+ HEADER_FIELDS = ("version", "id", "verifiers", "task")
27
+ """Sent once, when a trace first appears."""
28
+
29
+ LIST_FIELDS = (
30
+ "nodes",
31
+ "calls",
32
+ "request_rewrites",
33
+ "response_rewrites",
34
+ )
35
+ """Append-only: each delta carries the items past the sent count. Lists the library replaces
36
+ (`errors` on a retry, `extra_usage` on a rescore) are scalars instead, re-sent whole."""
37
+
38
+ SCALAR_FIELDS = tuple(
39
+ sorted(
40
+ {name for name, info in Trace.model_fields.items() if not info.exclude}.union(
41
+ Trace.model_computed_fields
42
+ ).difference(HEADER_FIELDS, LIST_FIELDS)
43
+ )
44
+ )
45
+ """Every other serialized field, derived values included: re-sent whole whenever its value changes."""
46
+
47
+ TRAINING_ARRAY_FIELDS = frozenset({"routed_experts", "sampling_mask", "top_logprobs"})
48
+ """Node fields holding per-token training arrays; never streamed."""
49
+
50
+
51
+ def dump(model: BaseModel, **kwargs: Any) -> dict:
52
+ # Dump the runtime type, so subclassed task data and agent configs keep their own fields.
53
+ return model.model_dump(mode="python", serialize_as_any=True, **kwargs)
54
+
55
+
56
+ class TraceCursor:
57
+ """What of one trace has been sent."""
58
+
59
+ def __init__(self, attempt: int) -> None:
60
+ self.attempt = attempt
61
+ """The attempt this cursor diffs: a retry keeps the trace id but not the attempt."""
62
+ self.sent = dict.fromkeys(LIST_FIELDS, 0)
63
+ self.links: list[int] = []
64
+ """Per sent node, how many of its semantic links have been sent."""
65
+ self.scalars: dict[str, Any] = {}
66
+ self.pending: list[dict] = []
67
+
68
+ def copy(self) -> TraceCursor:
69
+ """A copy safe to advance; the stored values themselves are never mutated."""
70
+ cursor = TraceCursor(self.attempt)
71
+ cursor.sent, cursor.links, cursor.scalars = (
72
+ dict(self.sent),
73
+ list(self.links),
74
+ dict(self.scalars),
75
+ )
76
+ cursor.pending = self.pending
77
+ return cursor
78
+
79
+
80
+ class DeltaStreamer:
81
+ """Sends the current traces' changes as deltas, one flush per burst of changes.
82
+
83
+ `watch` subscribes a trace; each `Trace.notify` schedules a flush, and changes landing in the
84
+ same loop iteration share it. Use as an async context manager around the run: a clean exit
85
+ flushes the final state, a failed one cancels pending sends. A cursor advances only once its
86
+ delta is sent, so a failed send is diffed again at the next flush."""
87
+
88
+ def __init__(
89
+ self,
90
+ traces: Callable[[], Iterable[Trace]],
91
+ send: Callable[[dict], Awaitable[None]],
92
+ ) -> None:
93
+ self.traces = traces
94
+ self.send = send
95
+ self.cursors: dict[str, TraceCursor] = {}
96
+ self._scheduled: asyncio.Handle | None = None
97
+ self._flushes: set[asyncio.Task] = set()
98
+ self._lock = asyncio.Lock()
99
+ self._closed = False
100
+
101
+ async def __aenter__(self) -> Self:
102
+ return self
103
+
104
+ async def __aexit__(self, exc_type, exc, tb) -> None:
105
+ self._closed = True # a trace notifying after the run sends nothing
106
+ if self._scheduled is not None:
107
+ self._scheduled.cancel()
108
+ self._scheduled = None
109
+ if exc_type is not None:
110
+ for task in self._flushes:
111
+ task.cancel()
112
+ await asyncio.gather(*self._flushes, return_exceptions=True)
113
+ if exc_type is None:
114
+ await self.flush()
115
+
116
+ def watch(self, trace: Trace) -> None:
117
+ # A plain function, not the bound method: grading deep-copies traces mid-run, and a
118
+ # bound method would drag this streamer (and its asyncio tasks) into the copy.
119
+ trace.watch(lambda changed: self._changed(changed))
120
+ self._changed(trace)
121
+
122
+ def _changed(self, trace: Trace) -> None:
123
+ if self._scheduled is None and not self._closed:
124
+ self._scheduled = asyncio.get_running_loop().call_soon(self._start_flush)
125
+
126
+ def _start_flush(self) -> None:
127
+ self._scheduled = None
128
+ task = asyncio.create_task(self.flush())
129
+ self._flushes.add(task)
130
+ task.add_done_callback(self._flushes.discard)
131
+
132
+ async def flush(self) -> None:
133
+ async with self._lock: # deltas must leave in diff order
134
+ for trace_id, delta, cursor in self.diff():
135
+ # The cursor stays put on failure: the next flush resends it.
136
+ try:
137
+ await self.send(delta)
138
+ except Exception as e:
139
+ logger.warning(
140
+ "Failed to send trace delta - %s: %s",
141
+ type(e).__name__,
142
+ clip(str(e)),
143
+ exc_info=logger.isEnabledFor(logging.DEBUG),
144
+ )
145
+ continue
146
+ if cursor is None:
147
+ self.cursors.pop(trace_id, None)
148
+ else:
149
+ self.cursors[trace_id] = cursor
150
+
151
+ def diff(self) -> list[tuple[str, dict, TraceCursor | None]]:
152
+ """Each trace's delta, with its cursor as it stands once that delta is sent (None for a
153
+ discard). Nothing is committed here: `flush` stores a cursor only after its send."""
154
+ traces = list(self.traces())
155
+ live = {trace.id for trace in traces}
156
+ # A trace that left the live set (a retried attempt) is discarded on the other side too.
157
+ deltas = [
158
+ (gone, {"trace": gone, "discard": True}, None)
159
+ for gone in self.cursors
160
+ if gone not in live
161
+ ]
162
+ for trace in traces:
163
+ delta: dict[str, Any] = {"trace": trace.id}
164
+ sent = self.cursors.get(trace.id)
165
+ if sent is not None and sent.attempt != trace.attempt:
166
+ sent = None # a retry's fresh trace under the same id: reopen it from scratch
167
+ cursor = sent.copy() if sent is not None else TraceCursor(trace.attempt)
168
+ if sent is None:
169
+ delta["open"] = dump(trace, include=set(HEADER_FIELDS))
170
+ links = {} # str keys: binary wire formats forbid int map keys
171
+ for index in range(cursor.sent["nodes"]):
172
+ node_links = trace.nodes[index].semantic_parents
173
+ if len(node_links) > cursor.links[index]:
174
+ links[str(index)] = [
175
+ dump(link) for link in node_links[cursor.links[index] :]
176
+ ]
177
+ cursor.links[index] = len(node_links)
178
+ if links:
179
+ delta["links"] = links
180
+ for field in LIST_FIELDS:
181
+ items = getattr(trace, field)[cursor.sent[field] :]
182
+ if not items:
183
+ continue
184
+ if field == "nodes":
185
+ # Per-token streams ride as raw-bytes arrays; training arrays stay behind.
186
+ delta[field] = [
187
+ dump(
188
+ node,
189
+ context={"token_arrays": True},
190
+ exclude=TRAINING_ARRAY_FIELDS,
191
+ )
192
+ for node in items
193
+ ]
194
+ cursor.links.extend(len(node.semantic_parents) for node in items)
195
+ else:
196
+ delta[field] = [dump(item) for item in items]
197
+ cursor.sent[field] += len(items)
198
+ changed = {
199
+ field: value
200
+ for field, value in dump(trace, include=set(SCALAR_FIELDS)).items()
201
+ if cursor.scalars.get(field, ...) != value
202
+ }
203
+ if changed:
204
+ cursor.scalars.update(changed)
205
+ delta["set"] = changed
206
+ pending = [dump(message) for message in trace.pending]
207
+ if pending != cursor.pending:
208
+ cursor.pending = delta["pending"] = pending
209
+ if len(delta) > 1:
210
+ deltas.append((trace.id, delta, cursor))
211
+ return deltas
212
+
213
+
214
+ class EpisodeAssembly:
215
+ """The receiving side: raw trace dicts in arrival order, each shaped like a dumped `Trace`
216
+ plus its `pending` preview. Validate one with `Trace.model_validate` once it is complete."""
217
+
218
+ def __init__(self) -> None:
219
+ self.traces: dict[str, dict] = {}
220
+
221
+ def apply(self, delta: dict) -> None:
222
+ trace_id = delta["trace"]
223
+ if delta.get("discard"):
224
+ self.traces.pop(trace_id, None)
225
+ return
226
+ trace = self.traces.get(trace_id)
227
+ # An `open` for a known id is a retry: start over.
228
+ if trace is None or "open" in delta:
229
+ trace = self.traces[trace_id] = {
230
+ **delta["open"],
231
+ **{f: [] for f in LIST_FIELDS},
232
+ "pending": [],
233
+ }
234
+ for index, links in (delta.get("links") or {}).items():
235
+ trace["nodes"][int(index)]["semantic_parents"].extend(links)
236
+ for field in LIST_FIELDS:
237
+ if field in delta:
238
+ # Nodes are copied, so a later `links` delta never mutates the delta the caller holds.
239
+ items = delta[field]
240
+ if field == "nodes":
241
+ items = [
242
+ {
243
+ **node,
244
+ "semantic_parents": list(
245
+ node.get("semantic_parents") or []
246
+ ),
247
+ }
248
+ for node in items
249
+ ]
250
+ trace[field].extend(items)
251
+ trace.update(delta.get("set") or {})
252
+ if "pending" in delta:
253
+ trace["pending"] = delta["pending"]
254
+
255
+
256
+ __all__ = ["DeltaStreamer", "EpisodeAssembly"]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: verifiers
3
- Version: 0.4.2.dev13
3
+ Version: 0.4.2.dev18
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
@@ -1,6 +1,7 @@
1
1
  verifiers/__init__.py,sha256=F5IVMw6mhGaPBMCw7QKk0la_r5mMwydP2hdTTdQucik,352
2
2
  verifiers/v1/__init__.py,sha256=gVnDxIQXsDjha93fZzdLw2b1G5i8i28drSf75JHmmHY,18617
3
3
  verifiers/v1/agent.py,sha256=3mRrubm2EwGIYexdJ9F0Lq5Uuta9-E_CC29Phh_9Vbw,48439
4
+ verifiers/v1/delta.py,sha256=IlZAOjBiaZDoDX7CHS8YuEMw70IYsMh7cRVCFsQveSg,10660
4
5
  verifiers/v1/env.py,sha256=UA1FdNd64XywIevJliNyL54afa2StN1ND6ro9HrjlVo,20566
5
6
  verifiers/v1/episode.py,sha256=ExeTkNEBsDuG40m6VogV6Gd4IHdO4SMPIzQSpt_V96U,6984
6
7
  verifiers/v1/errors.py,sha256=OieUBIOZ6FW7oKygbXIRoag6RrPxKYpMPfEYPcCnVVE,5863
@@ -192,8 +193,8 @@ verifiers/v1/utils/scope.py,sha256=zbs4pj6AVk4jywlAJ3AX0Q0_kzB9dBB02nY-9H4ELdQ,8
192
193
  verifiers/v1/utils/score.py,sha256=493yJVMw8teCu9JxapxMFPFzI0hNUqdo0Y2nGW4kckk,6200
193
194
  verifiers/v1/utils/trace_store.py,sha256=Qo9qvsJAl8PoRUavjQAfUB2VNxmUtYQtU2ejLKPzY9c,3382
194
195
  verifiers/v1/utils/version.py,sha256=-obEo_-l9-D8FLef4hYxncOe-uJpxrM1g2Hig_37Sgs,1607
195
- verifiers-0.4.2.dev13.dist-info/METADATA,sha256=kIfheb800edh61DIii36F5kanTVgGzgQjCbvG13jzHk,5137
196
- verifiers-0.4.2.dev13.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
197
- verifiers-0.4.2.dev13.dist-info/entry_points.txt,sha256=3M8Wr0w1cUKiB-fJ6YHB6eK5WuKYg-Y3OC4wCuUje_c,174
198
- verifiers-0.4.2.dev13.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
199
- verifiers-0.4.2.dev13.dist-info/RECORD,,
196
+ verifiers-0.4.2.dev18.dist-info/METADATA,sha256=TDc0avS1BRWlbiXL2L6gOsoYTLaNM7Rs2NXtc-yJu9g,5137
197
+ verifiers-0.4.2.dev18.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
198
+ verifiers-0.4.2.dev18.dist-info/entry_points.txt,sha256=3M8Wr0w1cUKiB-fJ6YHB6eK5WuKYg-Y3OC4wCuUje_c,174
199
+ verifiers-0.4.2.dev18.dist-info/licenses/LICENSE,sha256=v0RrUsdV3IDoZhrRce297IXS3xMHNJ-_LdLpFAUWb9k,1072
200
+ verifiers-0.4.2.dev18.dist-info/RECORD,,