ssapling 0.1.0__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.
- ssapling/__init__.py +12 -0
- ssapling/core/__init__.py +53 -0
- ssapling/core/_declarations.py +139 -0
- ssapling/core/_execution.py +155 -0
- ssapling/core/_plain.py +37 -0
- ssapling/core/_text.py +42 -0
- ssapling/core/errors.py +175 -0
- ssapling/core/loading.py +205 -0
- ssapling/core/registry.py +345 -0
- ssapling/core/settings.py +698 -0
- ssapling/core/spec.py +98 -0
- ssapling/data/__init__.py +89 -0
- ssapling/data/_matching.py +22 -0
- ssapling/data/batching.py +166 -0
- ssapling/data/collections.py +335 -0
- ssapling/data/encoding.py +107 -0
- ssapling/data/errors.py +104 -0
- ssapling/data/provenance.py +94 -0
- ssapling/data/records.py +546 -0
- ssapling/data/sampling.py +339 -0
- ssapling/data/storage.py +569 -0
- ssapling/environments/__init__.py +43 -0
- ssapling/environments/contracts.py +168 -0
- ssapling/environments/errors.py +53 -0
- ssapling/environments/runner.py +153 -0
- ssapling/environments/types.py +173 -0
- ssapling/evaluate/__init__.py +40 -0
- ssapling/evaluate/aggregation.py +173 -0
- ssapling/evaluate/assessment.py +429 -0
- ssapling/evaluate/measurement.py +165 -0
- ssapling/interaction/__init__.py +24 -0
- ssapling/interaction/episode.py +713 -0
- ssapling/interaction/errors.py +21 -0
- ssapling/interaction/hosting.py +287 -0
- ssapling/models/__init__.py +44 -0
- ssapling/models/buffering.py +189 -0
- ssapling/models/contracts.py +181 -0
- ssapling/models/errors.py +27 -0
- ssapling/models/types.py +75 -0
- ssapling/py.typed +0 -0
- ssapling/registries.py +37 -0
- ssapling/tasks/__init__.py +49 -0
- ssapling/tasks/contracts.py +137 -0
- ssapling/tasks/errors.py +37 -0
- ssapling/tasks/types.py +172 -0
- ssapling/teachers/__init__.py +34 -0
- ssapling/teachers/contracts.py +145 -0
- ssapling/teachers/errors.py +80 -0
- ssapling/teachers/runner.py +142 -0
- ssapling/teachers/types.py +178 -0
- ssapling/train/__init__.py +43 -0
- ssapling/train/components.py +194 -0
- ssapling/train/context.py +169 -0
- ssapling/train/errors.py +24 -0
- ssapling/train/procedure.py +316 -0
- ssapling/train/runner.py +398 -0
- ssapling/train/stages.py +463 -0
- ssapling-0.1.0.dist-info/METADATA +113 -0
- ssapling-0.1.0.dist-info/RECORD +61 -0
- ssapling-0.1.0.dist-info/WHEEL +4 -0
- ssapling-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
"""Procedures: which stages a run does, when, and when it stops.
|
|
2
|
+
|
|
3
|
+
A **procedure** lists entries, each a registered stage with its settings and
|
|
4
|
+
an optional trigger, and a stop condition. It is written in Python or read
|
|
5
|
+
from a file, and checked the same way::
|
|
6
|
+
|
|
7
|
+
procedure:
|
|
8
|
+
- stage: interact
|
|
9
|
+
settings: {episodes: 32}
|
|
10
|
+
- stage: learn_operation
|
|
11
|
+
every: {episodes: 500}
|
|
12
|
+
settings: {operation: consolidate}
|
|
13
|
+
stop: {episodes: 100000}
|
|
14
|
+
|
|
15
|
+
A **controller** decides what the run does next. The built-in
|
|
16
|
+
``FixedController`` follows the list.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from collections.abc import Awaitable, Iterable, Mapping
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from typing import Any, Protocol
|
|
22
|
+
|
|
23
|
+
from ..core import setting
|
|
24
|
+
from .components import ComponentEntry
|
|
25
|
+
from .context import COUNTERS, RunContext
|
|
26
|
+
from .errors import ProcedureStuckError
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"Condition",
|
|
30
|
+
"Controller",
|
|
31
|
+
"Decision",
|
|
32
|
+
"Entry",
|
|
33
|
+
"Every",
|
|
34
|
+
"FixedController",
|
|
35
|
+
"Procedure",
|
|
36
|
+
"ReplayController",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class _Counts:
|
|
42
|
+
"""The counters a trigger or a condition can name, and the run's time."""
|
|
43
|
+
|
|
44
|
+
episodes: int | None = setting(None, ge=1, description="Episodes run.")
|
|
45
|
+
steps: int | None = setting(None, ge=1, description="Environment steps taken.")
|
|
46
|
+
updates: int | None = setting(None, ge=1, description="Calls to a learning operation.")
|
|
47
|
+
stages: int | None = setting(None, ge=1, description="Stages started.")
|
|
48
|
+
seconds: float | None = setting(
|
|
49
|
+
None,
|
|
50
|
+
gt=0,
|
|
51
|
+
description="Seconds the run has been running. Unlike the counters, not reproducible.",
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
def named(self) -> dict[str, float]:
|
|
55
|
+
"""The counters given, with their numbers."""
|
|
56
|
+
return {
|
|
57
|
+
name: getattr(self, name)
|
|
58
|
+
for name in (*COUNTERS, "seconds")
|
|
59
|
+
if getattr(self, name) is not None
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class Every(_Counts):
|
|
65
|
+
"""A trigger: run each time a counter has grown by this much since the entry last ran.
|
|
66
|
+
|
|
67
|
+
Name exactly one counter, such as ``{episodes: 500}``. The first time,
|
|
68
|
+
the counter is counted from the start of the run.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def validate(self) -> None:
|
|
72
|
+
if len(self.named()) != 1:
|
|
73
|
+
raise ValueError("every names exactly one counter, such as {episodes: 500}")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True)
|
|
77
|
+
class Condition(_Counts):
|
|
78
|
+
"""Holds when any counter named has reached its number, or the value named is in bounds.
|
|
79
|
+
|
|
80
|
+
``{episodes: 100000}`` holds after 100000 episodes, and ``{value:
|
|
81
|
+
monitoring.accuracy, at_least: 0.95}`` once that published value is at
|
|
82
|
+
least 0.95. Given both, whichever comes first. A value not yet
|
|
83
|
+
published leaves the condition unmet, and so does an undefined one
|
|
84
|
+
(``None``), such as an aggregate over no values.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
value: str | None = setting(
|
|
88
|
+
None,
|
|
89
|
+
min_length=1,
|
|
90
|
+
description=(
|
|
91
|
+
"A published value, by its name or a dotted path into it, such as "
|
|
92
|
+
"'monitoring.accuracy'."
|
|
93
|
+
),
|
|
94
|
+
)
|
|
95
|
+
at_least: float | None = setting(None, description="The value has reached this.")
|
|
96
|
+
at_most: float | None = setting(None, description="The value has come down to this.")
|
|
97
|
+
|
|
98
|
+
def validate(self) -> None:
|
|
99
|
+
bounded = self.at_least is not None or self.at_most is not None
|
|
100
|
+
if self.value is None and bounded:
|
|
101
|
+
raise ValueError("at_least and at_most bound a value; name it in value")
|
|
102
|
+
if self.value is not None and not bounded:
|
|
103
|
+
raise ValueError(f"give the value {self.value!r} a bound: at_least or at_most")
|
|
104
|
+
if self.value is None and not self.named():
|
|
105
|
+
raise ValueError(
|
|
106
|
+
"a condition names a counter, such as {episodes: 1000}, or a value and a bound"
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def reads(self) -> str | None:
|
|
111
|
+
"""The name of the published value the condition reads, if any."""
|
|
112
|
+
return None if self.value is None else self.value.split(".")[0]
|
|
113
|
+
|
|
114
|
+
def holds(self, context: RunContext) -> bool:
|
|
115
|
+
"""Whether the condition holds in ``context`` now.
|
|
116
|
+
|
|
117
|
+
Raises:
|
|
118
|
+
LookupError: The value is published, but the path leads nowhere
|
|
119
|
+
in it (see ``RunContext.read``).
|
|
120
|
+
TypeError: The value is not a number.
|
|
121
|
+
"""
|
|
122
|
+
now = _now(context)
|
|
123
|
+
if any(now[name] >= limit for name, limit in self.named().items()):
|
|
124
|
+
return True
|
|
125
|
+
if self.value is None or self.reads not in context.values:
|
|
126
|
+
return False
|
|
127
|
+
value = context.read(self.value)
|
|
128
|
+
if value is None:
|
|
129
|
+
return False
|
|
130
|
+
if isinstance(value, bool) or not isinstance(value, int | float):
|
|
131
|
+
raise TypeError(f"{self.value!r} is {value!r}, not a number, so it has no bounds")
|
|
132
|
+
return (self.at_least is None or value >= self.at_least) and (
|
|
133
|
+
self.at_most is None or value <= self.at_most
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass(frozen=True)
|
|
138
|
+
class Entry:
|
|
139
|
+
"""One entry of a procedure: a registered stage, its settings, and when it runs.
|
|
140
|
+
|
|
141
|
+
It has at most one trigger. Without one, it runs each time the list
|
|
142
|
+
reaches it.
|
|
143
|
+
"""
|
|
144
|
+
|
|
145
|
+
stage: str = setting(min_length=1, description="The registered stage.")
|
|
146
|
+
settings: dict[str, Any] = setting(default_factory=dict, description="The stage's settings.")
|
|
147
|
+
once: bool = setting(False, description="Run the first time the list reaches it, only.")
|
|
148
|
+
every: Every | None = setting(
|
|
149
|
+
None, description="Run each time a counter has grown by this much since it last ran."
|
|
150
|
+
)
|
|
151
|
+
until: Condition | None = setting(
|
|
152
|
+
None, description="Run each time the list reaches it, until the condition holds."
|
|
153
|
+
)
|
|
154
|
+
when: Condition | None = setting(
|
|
155
|
+
None,
|
|
156
|
+
description="Run once: the first time the list reaches it while the condition holds.",
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
def validate(self) -> None:
|
|
160
|
+
triggers = [name for name in ("every", "until", "when") if getattr(self, name) is not None]
|
|
161
|
+
if self.once:
|
|
162
|
+
triggers.insert(0, "once")
|
|
163
|
+
if len(triggers) > 1:
|
|
164
|
+
raise ValueError(f"an entry has at most one trigger, got {', '.join(triggers)}")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@dataclass(frozen=True)
|
|
168
|
+
class Procedure:
|
|
169
|
+
"""The stages a run does, in order with their triggers, and when it stops.
|
|
170
|
+
|
|
171
|
+
It may also list the components the run builds, so that one file
|
|
172
|
+
describes the whole run.
|
|
173
|
+
"""
|
|
174
|
+
|
|
175
|
+
procedure: list[Entry] = setting(description="The entries, in order.")
|
|
176
|
+
stop: Condition = setting(
|
|
177
|
+
description=(
|
|
178
|
+
"When the run stops. It is checked before every stage, whatever the controller "
|
|
179
|
+
"decides, so it is also the run's budget."
|
|
180
|
+
)
|
|
181
|
+
)
|
|
182
|
+
components: dict[str, ComponentEntry] = setting(
|
|
183
|
+
default_factory=dict,
|
|
184
|
+
description="The components the run builds, by role, in the order they are built.",
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
Decision = Entry | Mapping[str, Any] | None
|
|
189
|
+
"""What a controller decides: an entry to run, as an ``Entry`` or a mapping of
|
|
190
|
+
its settings, or ``None`` to stop."""
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class Controller(Protocol):
|
|
194
|
+
"""Decides what a run does next: which stage, with which settings, or to stop.
|
|
195
|
+
|
|
196
|
+
It may also have ``export_state()`` and ``restore_state(state)``, so its
|
|
197
|
+
state is saved with each checkpoint.
|
|
198
|
+
"""
|
|
199
|
+
|
|
200
|
+
def decide(
|
|
201
|
+
self, context: RunContext, last_error: Exception | None
|
|
202
|
+
) -> Decision | Awaitable[Decision]:
|
|
203
|
+
"""The entry to run next, or ``None`` to stop. May be ``async def``.
|
|
204
|
+
|
|
205
|
+
The entry may be an ``Entry`` or a mapping of its settings, such as
|
|
206
|
+
``{"stage": "interact", "settings": {"episodes": 8}}``, and is
|
|
207
|
+
checked like an entry of a procedure. ``last_error`` says why the
|
|
208
|
+
previous decision was refused, or is ``None``. A refused decision
|
|
209
|
+
did not run, so the controller can choose again. Only the entry's
|
|
210
|
+
stage and settings are used; its trigger, if any, is the
|
|
211
|
+
controller's own business.
|
|
212
|
+
"""
|
|
213
|
+
...
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class FixedController:
|
|
217
|
+
"""Follows a procedure's list: goes through it again and again, running each entry that fires.
|
|
218
|
+
|
|
219
|
+
The run stops when the stop condition holds. If a whole pass through
|
|
220
|
+
the list finds nothing to run before that, it raises
|
|
221
|
+
``ProcedureStuckError`` instead of looping forever.
|
|
222
|
+
"""
|
|
223
|
+
|
|
224
|
+
def __init__(self, procedure: Procedure) -> None:
|
|
225
|
+
self.entries = tuple(procedure.procedure)
|
|
226
|
+
self.position = 0 # the next entry to consider
|
|
227
|
+
# The counters when each entry last ran; None if it has not.
|
|
228
|
+
self.last: list[dict[str, float] | None] = [None] * len(self.entries)
|
|
229
|
+
|
|
230
|
+
def decide(self, context: RunContext, last_error: Exception | None) -> Entry:
|
|
231
|
+
"""The next entry in the list whose trigger fires.
|
|
232
|
+
|
|
233
|
+
Raises:
|
|
234
|
+
ProcedureStuckError: No entry's trigger fires.
|
|
235
|
+
Exception: ``last_error``: the list was checked before the run,
|
|
236
|
+
so a refused entry cannot be chosen differently.
|
|
237
|
+
"""
|
|
238
|
+
if last_error is not None:
|
|
239
|
+
raise last_error
|
|
240
|
+
for _ in self.entries:
|
|
241
|
+
index = self.position
|
|
242
|
+
self.position = (index + 1) % len(self.entries)
|
|
243
|
+
if self._fires(index, context):
|
|
244
|
+
self.last[index] = _now(context)
|
|
245
|
+
return self.entries[index]
|
|
246
|
+
raise ProcedureStuckError(context.counters)
|
|
247
|
+
|
|
248
|
+
def export_state(self) -> dict[str, Any]:
|
|
249
|
+
"""Where it is in the list, and when each entry last ran, for a checkpoint."""
|
|
250
|
+
return {"position": self.position, "last": list(self.last)}
|
|
251
|
+
|
|
252
|
+
def restore_state(self, state: Mapping[str, Any]) -> None:
|
|
253
|
+
"""Return to what ``export_state`` saved."""
|
|
254
|
+
self.position, self.last = state["position"], list(state["last"])
|
|
255
|
+
|
|
256
|
+
def _fires(self, index: int, context: RunContext) -> bool:
|
|
257
|
+
entry, last = self.entries[index], self.last[index]
|
|
258
|
+
if entry.once:
|
|
259
|
+
return last is None
|
|
260
|
+
if entry.when is not None:
|
|
261
|
+
return last is None and entry.when.holds(context)
|
|
262
|
+
if entry.until is not None:
|
|
263
|
+
return not entry.until.holds(context)
|
|
264
|
+
if entry.every is not None:
|
|
265
|
+
((counter, amount),) = entry.every.named().items()
|
|
266
|
+
since = 0 if last is None else last[counter]
|
|
267
|
+
return _now(context)[counter] - since >= amount
|
|
268
|
+
return True
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
class ReplayController:
|
|
272
|
+
"""Makes a run's recorded decisions again, in order, then stops: whatever made them.
|
|
273
|
+
|
|
274
|
+
Example::
|
|
275
|
+
|
|
276
|
+
decisions = RecordStore("runs/llm").load_document("decisions")["decisions"]
|
|
277
|
+
await Runner(procedure, components, seed=7, controller=ReplayController(decisions)).run()
|
|
278
|
+
|
|
279
|
+
Args:
|
|
280
|
+
decisions: A run's decision log (see ``RunContext.decisions``).
|
|
281
|
+
The decisions that were refused are left out.
|
|
282
|
+
"""
|
|
283
|
+
|
|
284
|
+
def __init__(self, decisions: Iterable[Mapping[str, Any]]) -> None:
|
|
285
|
+
self.decisions = [
|
|
286
|
+
{"stage": decision["stage"], "settings": decision["settings"]}
|
|
287
|
+
for decision in decisions
|
|
288
|
+
if decision["refused"] is None
|
|
289
|
+
]
|
|
290
|
+
self.position = 0
|
|
291
|
+
|
|
292
|
+
def decide(self, context: RunContext, last_error: Exception | None) -> Decision:
|
|
293
|
+
"""The next recorded decision, or ``None`` after the last.
|
|
294
|
+
|
|
295
|
+
Raises:
|
|
296
|
+
Exception: ``last_error``: a recorded decision that cannot run
|
|
297
|
+
now cannot be replayed.
|
|
298
|
+
"""
|
|
299
|
+
if last_error is not None:
|
|
300
|
+
raise last_error
|
|
301
|
+
if self.position == len(self.decisions):
|
|
302
|
+
return None
|
|
303
|
+
self.position += 1
|
|
304
|
+
return self.decisions[self.position - 1]
|
|
305
|
+
|
|
306
|
+
def export_state(self) -> dict[str, int]:
|
|
307
|
+
"""How far it has replayed, for a checkpoint."""
|
|
308
|
+
return {"position": self.position}
|
|
309
|
+
|
|
310
|
+
def restore_state(self, state: Mapping[str, Any]) -> None:
|
|
311
|
+
"""Return to what ``export_state`` saved."""
|
|
312
|
+
self.position = state["position"]
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _now(context: RunContext) -> dict[str, float]:
|
|
316
|
+
return {**context.counters, "seconds": context.seconds}
|