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
ssapling/train/stages.py
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
"""Stages: the kinds of work a run does, each a registered component with its own settings.
|
|
2
|
+
|
|
3
|
+
A **stage** is anything with ``run(context)``, written as ``def`` or
|
|
4
|
+
``async def``, registered in ``stages``. It reads what it needs from the
|
|
5
|
+
run context and publishes values to it; it never hands anything to another
|
|
6
|
+
stage directly. It may also say what it needs, so a procedure that cannot
|
|
7
|
+
work is refused before the run starts:
|
|
8
|
+
|
|
9
|
+
- ``requires``: the components it uses, by role, such as ``("model",)``.
|
|
10
|
+
- ``reads``: the published values it reads, by name.
|
|
11
|
+
- ``publishes``: the values it publishes, by name.
|
|
12
|
+
- ``check(context)``: anything else, such as a learning operation the model
|
|
13
|
+
must support. It raises ``ValueError`` saying what is wrong.
|
|
14
|
+
|
|
15
|
+
These are read from the stage once it is built, so they may depend on its
|
|
16
|
+
settings. Built-in stages and a project's own are treated exactly alike::
|
|
17
|
+
|
|
18
|
+
class ReplayAudit:
|
|
19
|
+
requires = ("model", "store")
|
|
20
|
+
|
|
21
|
+
async def run(self, context):
|
|
22
|
+
...
|
|
23
|
+
|
|
24
|
+
stages.register("replay_audit", ReplayAudit)
|
|
25
|
+
|
|
26
|
+
The built-in stages are ``interact``, ``learn_from_data``,
|
|
27
|
+
``learn_operation``, ``update_sampler``, ``assess`` and ``checkpoint``.
|
|
28
|
+
Each learning call counts one update, and what the model's ``learn``
|
|
29
|
+
returns is published under the operation's name.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
import random
|
|
33
|
+
from collections.abc import Awaitable, Callable, Iterable
|
|
34
|
+
from dataclasses import dataclass
|
|
35
|
+
from typing import Any, Literal, Protocol
|
|
36
|
+
|
|
37
|
+
from ..core import Registry, setting
|
|
38
|
+
from ..core._declarations import name_of
|
|
39
|
+
from ..core._execution import Execution
|
|
40
|
+
from ..data import Collections, Record, RecordStep, batches
|
|
41
|
+
from ..environments import supports as environment_supports
|
|
42
|
+
from ..evaluate import save_results
|
|
43
|
+
from ..interaction import EpisodeSettings, run_episode, solve
|
|
44
|
+
from ..interaction.episode import OnStep
|
|
45
|
+
from ..models import filter_signals
|
|
46
|
+
from ..models import supports as model_supports
|
|
47
|
+
from ..teachers import supports as teacher_supports
|
|
48
|
+
from .context import RunContext
|
|
49
|
+
|
|
50
|
+
__all__ = ["Stage", "learn", "stages"]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Stage(Protocol):
|
|
54
|
+
"""What every stage provides: ``run(context)``."""
|
|
55
|
+
|
|
56
|
+
def run(self, context: RunContext) -> Awaitable[None] | None:
|
|
57
|
+
"""Do the stage's work, reading from ``context`` and publishing to it."""
|
|
58
|
+
...
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
stages: Registry[Callable[..., Stage]] = Registry("stage")
|
|
62
|
+
"""Registered stages. Also available as ``ssapling.registries.stages``."""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# Built-in stages
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class OnlineLearning:
|
|
70
|
+
"""Learning as the episodes happen: after each step, or after each episode."""
|
|
71
|
+
|
|
72
|
+
operation: str = setting(
|
|
73
|
+
"learn_from_experience", min_length=1, description="The learning operation called."
|
|
74
|
+
)
|
|
75
|
+
after: Literal["step", "episode"] = setting(
|
|
76
|
+
"step",
|
|
77
|
+
description=(
|
|
78
|
+
"step: after each step, with the step and the learning signals the model declares. "
|
|
79
|
+
"episode: after each episode, with its record."
|
|
80
|
+
),
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True)
|
|
85
|
+
class InteractSettings:
|
|
86
|
+
"""Settings for the interact stage."""
|
|
87
|
+
|
|
88
|
+
episodes: int = setting(1, ge=1, description="How many episodes to run.")
|
|
89
|
+
environment: str | None = setting(
|
|
90
|
+
"environment",
|
|
91
|
+
description="The environment's role. None: static solving, with no environment.",
|
|
92
|
+
)
|
|
93
|
+
teacher: str | None = setting(
|
|
94
|
+
None, description="The role of a teacher to consult at each step. None: no teacher."
|
|
95
|
+
)
|
|
96
|
+
teacher_context: str | None = setting(
|
|
97
|
+
None,
|
|
98
|
+
description=(
|
|
99
|
+
"The role of a function that builds each teacher request's context, as for "
|
|
100
|
+
"run_episode. None: the default context."
|
|
101
|
+
),
|
|
102
|
+
)
|
|
103
|
+
sampler: str = setting(
|
|
104
|
+
"sampler", min_length=1, description="The role of the sampler that picks each instance."
|
|
105
|
+
)
|
|
106
|
+
collections: str | None = setting(
|
|
107
|
+
"collections",
|
|
108
|
+
description=(
|
|
109
|
+
"The role of the collections whose problems are never trained on: each instance "
|
|
110
|
+
"comes from their remainder. None: the run has none."
|
|
111
|
+
),
|
|
112
|
+
)
|
|
113
|
+
episode: EpisodeSettings = setting(
|
|
114
|
+
default_factory=EpisodeSettings,
|
|
115
|
+
description="How each episode runs: timing, max_steps, intervene, threads.",
|
|
116
|
+
)
|
|
117
|
+
learn: OnlineLearning | None = setting(
|
|
118
|
+
None, description="Learn as the episodes happen. None: no learning in this stage."
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class Interact:
|
|
123
|
+
"""Runs episodes of the model, each on a new instance from the training remainder.
|
|
124
|
+
|
|
125
|
+
Each episode's instance is drawn from the remainder of the run's
|
|
126
|
+
collections, so it is never a problem of an assessment. Its seeds are
|
|
127
|
+
derived from the root seed and the episode's number, so a resumed run
|
|
128
|
+
draws the same instances. Records go to the run's store, if it has one,
|
|
129
|
+
as ``"episode-<number>"``. Counts episodes and steps.
|
|
130
|
+
"""
|
|
131
|
+
|
|
132
|
+
Settings = InteractSettings
|
|
133
|
+
|
|
134
|
+
def __init__(self, config: InteractSettings) -> None:
|
|
135
|
+
self.config = config
|
|
136
|
+
roles = (config.environment, config.teacher, config.teacher_context, config.collections)
|
|
137
|
+
self.requires = ("model", config.sampler, *(role for role in roles if role))
|
|
138
|
+
self.publishes = (config.learn.operation,) if config.learn else ()
|
|
139
|
+
|
|
140
|
+
def check(self, context: RunContext) -> None:
|
|
141
|
+
if self.config.learn is not None:
|
|
142
|
+
_check_learns(context, self.config.learn.operation)
|
|
143
|
+
if self.config.teacher is not None:
|
|
144
|
+
operation = self.config.episode.teacher_operation
|
|
145
|
+
if not teacher_supports(context.components[self.config.teacher], operation):
|
|
146
|
+
raise ValueError(f"the teacher does not support {operation!r}")
|
|
147
|
+
|
|
148
|
+
async def run(self, context: RunContext) -> None:
|
|
149
|
+
config = self.config
|
|
150
|
+
model, sampler = context.components["model"], context.components[config.sampler]
|
|
151
|
+
env = _role(context, config.environment)
|
|
152
|
+
collections = _role(context, config.collections)
|
|
153
|
+
if collections is None: # nothing reserved: draw from the sampler's source alone
|
|
154
|
+
collections = Collections(sampler.source)
|
|
155
|
+
on_step = self._on_step(context)
|
|
156
|
+
for _ in range(config.episodes):
|
|
157
|
+
number = context.counters["episodes"]
|
|
158
|
+
seed = context.seed(f"draw-{number}")
|
|
159
|
+
drawn = next(collections.remainder(sampler=sampler, seed=seed))
|
|
160
|
+
common: dict[str, Any] = {
|
|
161
|
+
"record_id": context.output_name(f"episode-{number}"),
|
|
162
|
+
"provenance": drawn.provenance,
|
|
163
|
+
"store": context.components.get("store"),
|
|
164
|
+
"settings": config.episode,
|
|
165
|
+
"on_step": on_step,
|
|
166
|
+
}
|
|
167
|
+
if env is None:
|
|
168
|
+
record = await solve(model, drawn.instance, **common)
|
|
169
|
+
else:
|
|
170
|
+
seeded = environment_supports(env, "seeded_reset")
|
|
171
|
+
record = await run_episode(
|
|
172
|
+
env,
|
|
173
|
+
model,
|
|
174
|
+
drawn.instance,
|
|
175
|
+
seed=context.seed(f"episode-{number}") if seeded else None,
|
|
176
|
+
teacher=_role(context, config.teacher),
|
|
177
|
+
teacher_context=_role(context, config.teacher_context),
|
|
178
|
+
**common,
|
|
179
|
+
)
|
|
180
|
+
context.counters["episodes"] += 1
|
|
181
|
+
context.counters["steps"] += len(record.steps)
|
|
182
|
+
if config.learn is not None and config.learn.after == "episode":
|
|
183
|
+
await learn(context, config.learn.operation, record=record)
|
|
184
|
+
|
|
185
|
+
def _on_step(self, context: RunContext) -> OnStep | None:
|
|
186
|
+
online = self.config.learn
|
|
187
|
+
if online is None or online.after != "step":
|
|
188
|
+
return None
|
|
189
|
+
model = context.components["model"]
|
|
190
|
+
operation = online.operation
|
|
191
|
+
|
|
192
|
+
async def learn_from(step: RecordStep) -> None:
|
|
193
|
+
signals = filter_signals(model, _signals(step))
|
|
194
|
+
await learn(context, operation, step=step, signals=signals)
|
|
195
|
+
|
|
196
|
+
return learn_from
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
@dataclass(frozen=True)
|
|
200
|
+
class LearnFromDataSettings:
|
|
201
|
+
"""Settings for the learn_from_data stage."""
|
|
202
|
+
|
|
203
|
+
source: str = setting(
|
|
204
|
+
min_length=1,
|
|
205
|
+
description=(
|
|
206
|
+
"The role of what the items come from: a store, whose finished records are the "
|
|
207
|
+
"items, except attempts at instances of a collection; or any finite collection of "
|
|
208
|
+
"items, such as a list of records or a collection's instances."
|
|
209
|
+
),
|
|
210
|
+
)
|
|
211
|
+
operation: str = setting(
|
|
212
|
+
"learn_from_batch", min_length=1, description="The learning operation called per batch."
|
|
213
|
+
)
|
|
214
|
+
batches: int = setting(1, ge=1, description="How many batches: one update each.")
|
|
215
|
+
batch_size: int = setting(
|
|
216
|
+
32, ge=1, description="Items per batch, drawn at random, with replacement."
|
|
217
|
+
)
|
|
218
|
+
collator: str | None = setting(
|
|
219
|
+
None,
|
|
220
|
+
description=(
|
|
221
|
+
"The role of a collator, which turns a list of items into a batch. None: the batch "
|
|
222
|
+
"is the list."
|
|
223
|
+
),
|
|
224
|
+
)
|
|
225
|
+
workers: int = setting(0, ge=0, description="Worker processes that collate; 0 collates here.")
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class LearnFromData:
|
|
229
|
+
"""Draws batches from a data source and calls a learning operation with each.
|
|
230
|
+
|
|
231
|
+
Items are drawn at random, with replacement, with a seed derived from
|
|
232
|
+
the root seed and the updates so far. Each batch is passed as
|
|
233
|
+
``learn(operation, batch=...)`` and counts one update.
|
|
234
|
+
"""
|
|
235
|
+
|
|
236
|
+
Settings = LearnFromDataSettings
|
|
237
|
+
|
|
238
|
+
def __init__(self, config: LearnFromDataSettings) -> None:
|
|
239
|
+
self.config = config
|
|
240
|
+
self.requires = ("model", config.source, *([config.collator] if config.collator else []))
|
|
241
|
+
self.publishes = (config.operation,)
|
|
242
|
+
|
|
243
|
+
def check(self, context: RunContext) -> None:
|
|
244
|
+
_check_learns(context, self.config.operation)
|
|
245
|
+
source = context.components[self.config.source]
|
|
246
|
+
if not (_is_store(source) or isinstance(source, Iterable)):
|
|
247
|
+
raise ValueError(f"{self.config.source!r} is neither a store nor a collection of items")
|
|
248
|
+
|
|
249
|
+
async def run(self, context: RunContext) -> None:
|
|
250
|
+
config = self.config
|
|
251
|
+
items = _items(context.components[config.source])
|
|
252
|
+
if not items:
|
|
253
|
+
raise ValueError(f"{config.source!r} has no items to learn from")
|
|
254
|
+
rng = random.Random(context.seed(f"batches-{context.counters['updates']}"))
|
|
255
|
+
drawn = (rng.choice(items) for _ in range(config.batches * config.batch_size))
|
|
256
|
+
collate = context.components[config.collator] if config.collator else list
|
|
257
|
+
for batch in batches(drawn, collate, batch_size=config.batch_size, workers=config.workers):
|
|
258
|
+
await learn(context, config.operation, batch=batch)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
@dataclass(frozen=True)
|
|
262
|
+
class LearnOperationSettings:
|
|
263
|
+
"""Settings for the learn_operation stage."""
|
|
264
|
+
|
|
265
|
+
operation: str = setting(
|
|
266
|
+
min_length=1, description="The learning operation, such as 'consolidate'."
|
|
267
|
+
)
|
|
268
|
+
payload: dict[str, Any] = setting(
|
|
269
|
+
default_factory=dict,
|
|
270
|
+
description="Its arguments, as plain values, such as {limits: {seconds: 600}}.",
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
class LearnOperation:
|
|
275
|
+
"""Calls one learning operation, such as a night-cycle consolidation, once.
|
|
276
|
+
|
|
277
|
+
It is called as ``learn(operation, **payload)``, and counts one update.
|
|
278
|
+
"""
|
|
279
|
+
|
|
280
|
+
Settings = LearnOperationSettings
|
|
281
|
+
requires = ("model",)
|
|
282
|
+
|
|
283
|
+
def __init__(self, config: LearnOperationSettings) -> None:
|
|
284
|
+
self.config = config
|
|
285
|
+
self.publishes = (config.operation,)
|
|
286
|
+
|
|
287
|
+
def check(self, context: RunContext) -> None:
|
|
288
|
+
_check_learns(context, self.config.operation)
|
|
289
|
+
|
|
290
|
+
async def run(self, context: RunContext) -> None:
|
|
291
|
+
await learn(context, self.config.operation, **self.config.payload)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
@dataclass(frozen=True)
|
|
295
|
+
class UpdateSamplerSettings:
|
|
296
|
+
"""Settings for the update_sampler stage."""
|
|
297
|
+
|
|
298
|
+
weights: dict[str, float] = setting(
|
|
299
|
+
description=(
|
|
300
|
+
"The sampler's new weights, keyed by value or stratum as a string, as for the "
|
|
301
|
+
"built-in samplers."
|
|
302
|
+
)
|
|
303
|
+
)
|
|
304
|
+
sampler: str = setting("sampler", min_length=1, description="The role of the sampler.")
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
class UpdateSampler:
|
|
308
|
+
"""Gives a sampler new weights, for a curriculum's next step.
|
|
309
|
+
|
|
310
|
+
Usually triggered with ``when``, by a condition on a published value.
|
|
311
|
+
"""
|
|
312
|
+
|
|
313
|
+
Settings = UpdateSamplerSettings
|
|
314
|
+
|
|
315
|
+
def __init__(self, config: UpdateSamplerSettings) -> None:
|
|
316
|
+
self.config = config
|
|
317
|
+
self.requires = (config.sampler,)
|
|
318
|
+
|
|
319
|
+
def check(self, context: RunContext) -> None:
|
|
320
|
+
if not callable(getattr(context.components[self.config.sampler], "set_weights", None)):
|
|
321
|
+
raise ValueError(f"the sampler {self.config.sampler!r} has no set_weights method")
|
|
322
|
+
|
|
323
|
+
def run(self, context: RunContext) -> None:
|
|
324
|
+
context.components[self.config.sampler].set_weights(self.config.weights)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
@dataclass(frozen=True)
|
|
328
|
+
class AssessSettings:
|
|
329
|
+
"""Settings for the assess stage."""
|
|
330
|
+
|
|
331
|
+
assessment: str = setting(
|
|
332
|
+
min_length=1,
|
|
333
|
+
description=(
|
|
334
|
+
"The role of the assessment to run. Its aggregates are published under this name."
|
|
335
|
+
),
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
class Assess:
|
|
340
|
+
"""Runs an assessment of the model, saves the results, and publishes the aggregates.
|
|
341
|
+
|
|
342
|
+
The assessment's run id is ``"<role>-<stages>"``, and its seed is
|
|
343
|
+
derived from the root seed and the role, so each time it runs it is
|
|
344
|
+
given the same seed. The results' model information is the run's
|
|
345
|
+
counters, and they are saved in the run's store, if it has one. The
|
|
346
|
+
aggregates' values are published under the role, as
|
|
347
|
+
``{"accuracy": 0.83, ...}``.
|
|
348
|
+
"""
|
|
349
|
+
|
|
350
|
+
Settings = AssessSettings
|
|
351
|
+
|
|
352
|
+
def __init__(self, config: AssessSettings) -> None:
|
|
353
|
+
self.config = config
|
|
354
|
+
self.requires = ("model", config.assessment)
|
|
355
|
+
self.publishes = (config.assessment,)
|
|
356
|
+
|
|
357
|
+
async def run(self, context: RunContext) -> None:
|
|
358
|
+
role = self.config.assessment
|
|
359
|
+
results = await Execution().call(
|
|
360
|
+
context.components[role].run,
|
|
361
|
+
context.components["model"],
|
|
362
|
+
run_id=context.output_name(f"{role}-{context.counters['stages']}"),
|
|
363
|
+
seed=context.seed(f"assessment-{role}"),
|
|
364
|
+
model_info=dict(context.counters),
|
|
365
|
+
)
|
|
366
|
+
store = context.components.get("store")
|
|
367
|
+
if store is not None:
|
|
368
|
+
save_results(store, results)
|
|
369
|
+
aggregates = {name: summary.value for name, summary in results.aggregates.items()}
|
|
370
|
+
context.publish(role, aggregates)
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
class Checkpoint:
|
|
374
|
+
"""Saves the run, so it can be resumed from here.
|
|
375
|
+
|
|
376
|
+
It saves, as the store document ``"checkpoints/<stages>"``, the state of
|
|
377
|
+
every component that exports it, the controller's, and the run
|
|
378
|
+
context's: its counters, running time, published values and decisions.
|
|
379
|
+
"""
|
|
380
|
+
|
|
381
|
+
requires = ("store",)
|
|
382
|
+
|
|
383
|
+
async def run(self, context: RunContext) -> None:
|
|
384
|
+
states = {}
|
|
385
|
+
for role, component in context.components.items():
|
|
386
|
+
export = getattr(component, "export_state", None)
|
|
387
|
+
if callable(export):
|
|
388
|
+
states[role] = await Execution().call(export)
|
|
389
|
+
export = getattr(context.controller, "export_state", None)
|
|
390
|
+
document = {
|
|
391
|
+
"context": context.export_state(),
|
|
392
|
+
"decisions": context.decisions,
|
|
393
|
+
"controller": await Execution().call(export) if callable(export) else None,
|
|
394
|
+
"components": states,
|
|
395
|
+
}
|
|
396
|
+
name = context.output_name(f"checkpoints/{context.counters['stages']}")
|
|
397
|
+
context.components["store"].save_document(name, document)
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
stages.register("interact", Interact)
|
|
401
|
+
stages.register("learn_from_data", LearnFromData)
|
|
402
|
+
stages.register("learn_operation", LearnOperation)
|
|
403
|
+
stages.register("update_sampler", UpdateSampler)
|
|
404
|
+
stages.register("assess", Assess)
|
|
405
|
+
stages.register("checkpoint", Checkpoint)
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
# Helpers
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
async def learn(context: RunContext, operation: str, **payload: Any) -> Any:
|
|
412
|
+
"""Call the run's model's learning operation ``operation`` with ``payload``, count the update,
|
|
413
|
+
and publish what it returns, its statistics, under the operation's name; then return them.
|
|
414
|
+
|
|
415
|
+
The built-in stages learn through it, and a downstream project's stages can too, so every
|
|
416
|
+
stage counts and publishes its updates alike. A model's ``learn`` may be ``async def``.
|
|
417
|
+
Nothing is published when it returns ``None``.
|
|
418
|
+
"""
|
|
419
|
+
stats = await Execution().call(context.components["model"].learn, operation, **payload)
|
|
420
|
+
context.counters["updates"] += 1
|
|
421
|
+
if stats is not None:
|
|
422
|
+
context.publish(operation, stats)
|
|
423
|
+
return stats
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _role(context: RunContext, role: str | None) -> Any:
|
|
427
|
+
"""The component with ``role``, or ``None`` when no role is set."""
|
|
428
|
+
return None if role is None else context.components[role]
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _check_learns(context: RunContext, operation: str) -> None:
|
|
432
|
+
model = context.components["model"]
|
|
433
|
+
if not model_supports(model, operation):
|
|
434
|
+
raise ValueError(f"the model, {name_of(model)}, does not support {operation!r}")
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def _signals(step: RecordStep) -> dict[str, Any]:
|
|
438
|
+
"""A step's learning signals, by name and then by agent: rewards and the teacher's answers."""
|
|
439
|
+
signals: dict[str, Any] = {}
|
|
440
|
+
if step.transition is not None and step.transition.rewards is not None:
|
|
441
|
+
signals["reward"] = dict(step.transition.rewards)
|
|
442
|
+
for response in step.teacher_responses:
|
|
443
|
+
if response.status == "answered":
|
|
444
|
+
for kind, by_agent in response.contributions.items():
|
|
445
|
+
signals.setdefault(kind, {}).update(by_agent)
|
|
446
|
+
return signals
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _is_store(source: object) -> bool:
|
|
450
|
+
return callable(getattr(source, "record_ids", None)) and callable(getattr(source, "read", None))
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def _items(source: Any) -> list[Any]:
|
|
454
|
+
"""A store's finished records, except attempts at instances of a collection; or the items."""
|
|
455
|
+
if not _is_store(source):
|
|
456
|
+
return list(source)
|
|
457
|
+
records: Iterable[Record] = (source.read(record_id) for record_id in source.record_ids())
|
|
458
|
+
return [
|
|
459
|
+
record
|
|
460
|
+
for record in records
|
|
461
|
+
if record.finished
|
|
462
|
+
and (record.header.provenance is None or record.header.provenance.collection is None)
|
|
463
|
+
]
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: ssapling
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Infrastructure, interfaces and scaffolding for System-Specification Alignment Problem projects.
|
|
5
|
+
Project-URL: Repository, https://github.com/KobeKnowles/SSAPling
|
|
6
|
+
Project-URL: Documentation, https://github.com/KobeKnowles/SSAPling/blob/main/docs/overview.md
|
|
7
|
+
Project-URL: Changelog, https://github.com/KobeKnowles/SSAPling/blob/main/CHANGELOG.md
|
|
8
|
+
Project-URL: Issues, https://github.com/KobeKnowles/SSAPling/issues
|
|
9
|
+
Author: Kobe Knowles
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: alignment,evaluation,machine learning,reinforcement learning,training
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.12
|
|
21
|
+
Provides-Extra: yaml
|
|
22
|
+
Requires-Dist: pyyaml>=6.0; extra == 'yaml'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# SSAPling
|
|
26
|
+
|
|
27
|
+
SSAPling is a Python library for the System–Specification Alignment Problem.
|
|
28
|
+
|
|
29
|
+
It provides general infrastructure, interfaces, and scaffolding for downstream
|
|
30
|
+
projects, such as one that teaches arithmetic or one on ARC. It defines how
|
|
31
|
+
environments, tasks, teachers, and models plug together, and it runs what is
|
|
32
|
+
common to every project: building components from settings, running episodes,
|
|
33
|
+
storing records, training procedures, and assessments. Concrete environments,
|
|
34
|
+
tasks, teachers, models, and learning methods live in downstream projects.
|
|
35
|
+
|
|
36
|
+
> **Status:** alpha. Every area is built and tested. Before 1.0, a minor
|
|
37
|
+
> release may change the public interface, and every such change is listed in
|
|
38
|
+
> the [changelog](https://github.com/KobeKnowles/SSAPling/blob/main/CHANGELOG.md).
|
|
39
|
+
|
|
40
|
+
## Installation
|
|
41
|
+
|
|
42
|
+
Requires Python 3.12 or newer. The base install has no third-party dependencies.
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install ssapling
|
|
46
|
+
pip install "ssapling[yaml]" # adds YAML configuration files
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
To work on SSAPling and a downstream project together, install it from a clone
|
|
50
|
+
in editable mode, so changes to SSAPling show up at once:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
uv add --editable ../SSAPling # or: pip install -e "../SSAPling[yaml]"
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Quick start
|
|
57
|
+
|
|
58
|
+
[`examples/arithmetic/`](https://github.com/KobeKnowles/SSAPling/blob/main/examples/arithmetic/)
|
|
59
|
+
is a complete small project: a learner that knows no arithmetic learns addition
|
|
60
|
+
from a tutor, and is assessed on problems it never trained on. From a clone:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
uv sync
|
|
64
|
+
uv run python examples/arithmetic/run.py
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
[Using SSAPling](https://github.com/KobeKnowles/SSAPling/blob/main/docs/usage.md)
|
|
68
|
+
walks through it part by part.
|
|
69
|
+
|
|
70
|
+
## Documentation
|
|
71
|
+
|
|
72
|
+
- [Overview](https://github.com/KobeKnowles/SSAPling/blob/main/docs/overview.md):
|
|
73
|
+
the package areas, their import rules, the packaging commitments, and a
|
|
74
|
+
glossary.
|
|
75
|
+
- [Using SSAPling](https://github.com/KobeKnowles/SSAPling/blob/main/docs/usage.md):
|
|
76
|
+
a whole project, from components to an assessed training run.
|
|
77
|
+
- [Extending SSAPling](https://github.com/KobeKnowles/SSAPling/blob/main/docs/extending.md):
|
|
78
|
+
what each kind of component needs, and how to change SSAPling's defaults.
|
|
79
|
+
|
|
80
|
+
The area guides:
|
|
81
|
+
|
|
82
|
+
- [Core](https://github.com/KobeKnowles/SSAPling/blob/main/docs/core.md):
|
|
83
|
+
registries, settings, configuration files, and building components.
|
|
84
|
+
- [Tasks](https://github.com/KobeKnowles/SSAPling/blob/main/docs/tasks.md):
|
|
85
|
+
instances, generated and enumerated tasks, scoring, partial checks, and
|
|
86
|
+
teaching resources.
|
|
87
|
+
- [Teachers](https://github.com/KobeKnowles/SSAPling/blob/main/docs/teachers.md):
|
|
88
|
+
requests and responses, the teacher contract, the runner, and checking a
|
|
89
|
+
teacher's requirements.
|
|
90
|
+
- [Models](https://github.com/KobeKnowles/SSAPling/blob/main/docs/models.md):
|
|
91
|
+
acting (act-only or buffered), participants and lanes, state, learning
|
|
92
|
+
operations, learning signals, and descriptions.
|
|
93
|
+
- [Environments](https://github.com/KobeKnowles/SSAPling/blob/main/docs/environments.md):
|
|
94
|
+
reset and step results, turn order, capabilities, the runner, and how to
|
|
95
|
+
write an adapter.
|
|
96
|
+
- [Data](https://github.com/KobeKnowles/SSAPling/blob/main/docs/data.md):
|
|
97
|
+
records, sources, samplers, collections that never share a problem,
|
|
98
|
+
provenance, storage, codecs, and batching.
|
|
99
|
+
- [Interaction](https://github.com/KobeKnowles/SSAPling/blob/main/docs/interaction.md):
|
|
100
|
+
the episode loop, timing, lanes, static solving, and running a component in
|
|
101
|
+
another process.
|
|
102
|
+
- [Evaluate](https://github.com/KobeKnowles/SSAPling/blob/main/docs/evaluate.md):
|
|
103
|
+
assessments, measurements, aggregation, and results.
|
|
104
|
+
- [Train](https://github.com/KobeKnowles/SSAPling/blob/main/docs/train.md):
|
|
105
|
+
procedures, stages, run files, checkpoints and resuming, and controllers.
|
|
106
|
+
|
|
107
|
+
[Development](https://github.com/KobeKnowles/SSAPling/blob/main/docs/development.md)
|
|
108
|
+
covers working on SSAPling itself.
|
|
109
|
+
|
|
110
|
+
## License
|
|
111
|
+
|
|
112
|
+
Apache License 2.0. See
|
|
113
|
+
[LICENSE](https://github.com/KobeKnowles/SSAPling/blob/main/LICENSE).
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
ssapling/__init__.py,sha256=F4FJh-NazK3MuFjG0QaZ8pxlXdZKNtDTttEGXYO1dUo,424
|
|
2
|
+
ssapling/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
ssapling/registries.py,sha256=Y5OdS7GKyml31fc-G2yEnWIGIfnC5J5kIQAua_pFb6Y,986
|
|
4
|
+
ssapling/core/__init__.py,sha256=yDImlUwicI6unzZv5TPL7AelTzdEtga2XikvdhmhKU4,1225
|
|
5
|
+
ssapling/core/_declarations.py,sha256=dtQIne73Cu-x-LTphbH9XVva-ik7p9qFONRh9IWJ68Q,5594
|
|
6
|
+
ssapling/core/_execution.py,sha256=rgzyFehweYxL3aVx2G-RFH4G-UNXOFn9GqAgKXRV-Co,6831
|
|
7
|
+
ssapling/core/_plain.py,sha256=-cbCwYfvl208Vp9q2OpgC42qzIvAWkz9Y998wP8iFMQ,1488
|
|
8
|
+
ssapling/core/_text.py,sha256=VNoJnbw9nG8HkHmp0nKzEnp59pjQ3qvaIyZYc6GooCk,1477
|
|
9
|
+
ssapling/core/errors.py,sha256=pH4tSE-ZgLbsr9cw9zCYl_1IdWKZYyFklNRju6FybQY,6245
|
|
10
|
+
ssapling/core/loading.py,sha256=L7D2rzaNRNJFjiKxT5TGVQmIK0JiR3JNVYQ9qkoVyJU,7916
|
|
11
|
+
ssapling/core/registry.py,sha256=I8tI9dkQC08JNMPAqxtuizyeTFIRgMIZ87ewWbMKTZ8,13049
|
|
12
|
+
ssapling/core/settings.py,sha256=J52z9-DJNCuAOPBS-sw--WeesNY_NANIUBKYsyFdLXg,25533
|
|
13
|
+
ssapling/core/spec.py,sha256=Snkk90y77t_AiGpo0w1K5pN_qJGQBXTQYXDZTtvJy9c,3734
|
|
14
|
+
ssapling/data/__init__.py,sha256=TVrFZaGCcjrEW7c4CoF6e0Rxe6Bh7lS4SBBWbnn9Nhw,1890
|
|
15
|
+
ssapling/data/_matching.py,sha256=1hIEWzM_Et4TAPzJVtB8BHiWNIPiTZ9Smu-V8kAM6e4,822
|
|
16
|
+
ssapling/data/batching.py,sha256=0QTvRmKE8NShooMjzVZvbZnma89GocNeTJAuzqHq0j0,6385
|
|
17
|
+
ssapling/data/collections.py,sha256=W581gePP_-sltPqw1ixFCrn_L8ZtbXGExu-Ft03RGvs,13475
|
|
18
|
+
ssapling/data/encoding.py,sha256=PoZpor67Cxn9137k2ynCrPl9GFhCQ6eNT3AXTyNAJsk,4062
|
|
19
|
+
ssapling/data/errors.py,sha256=LTmROqWmsBsPwD5gDFH-GN1l6AA68LGXaJRKITI8FUM,3691
|
|
20
|
+
ssapling/data/provenance.py,sha256=I80ItmHul8g_iwNx4S9q_MUZeUsIhaC4qdtcEnyFilE,4153
|
|
21
|
+
ssapling/data/records.py,sha256=lW5VOa6D3E9DS1L1F5_dN_8X41VwlP55b2VCc1ewNmo,23525
|
|
22
|
+
ssapling/data/sampling.py,sha256=7wAJLGK6ADx3fQ5YgjJYUSVrx30xFlP2aNvKu3wZCNQ,13720
|
|
23
|
+
ssapling/data/storage.py,sha256=EgFD_ninhEiEDKD_dFUECFldVRtSkpmaWXlfJjJltOM,22443
|
|
24
|
+
ssapling/environments/__init__.py,sha256=qAFahvsgRE_5dJbekPNPts-5zv8gINouaTkBaZxgRzA,1074
|
|
25
|
+
ssapling/environments/contracts.py,sha256=J0esdZNp8sgrueu6gPQIb5RVmxB_CqoiNg-TsqjanKg,6616
|
|
26
|
+
ssapling/environments/errors.py,sha256=lrFayKx8UY1j38oJud7G3le_UidUJ7R5avQ-egU3fDM,2118
|
|
27
|
+
ssapling/environments/runner.py,sha256=zpQKt-QsEc03230nv7bSu3Ls8qwDrA023rGfFGsjpqA,6485
|
|
28
|
+
ssapling/environments/types.py,sha256=RTRZcPS60byjUrQ5R6D5vZQNj5dDIA6-Nd-YNTjWSR8,8083
|
|
29
|
+
ssapling/evaluate/__init__.py,sha256=fAlJRjbuZFITM2-fKM2AcYAY06Iq-8Iz0BtCEk3CHvE,929
|
|
30
|
+
ssapling/evaluate/aggregation.py,sha256=z4n8glIbD-M_sgVHh7852K3HgAht6lF_Xa28mZTyaS0,7086
|
|
31
|
+
ssapling/evaluate/assessment.py,sha256=EtlOSaY0Y-rwz1vQjQN0q8OIkQabGX720PWInLNEa2E,16110
|
|
32
|
+
ssapling/evaluate/measurement.py,sha256=Y2_zQ4KwRCzH_TplQJWIeJGgPtBQc7Ae_kjQGGrspL0,5818
|
|
33
|
+
ssapling/interaction/__init__.py,sha256=qbyym8Mqjl4yCMvObhzrhx8diyJjaILhslSIOeYpnCo,625
|
|
34
|
+
ssapling/interaction/episode.py,sha256=fOEHGLqhcj35tCo6GHel9XOpdLqVKPaL25nXZ9Fya84,30166
|
|
35
|
+
ssapling/interaction/errors.py,sha256=aa5QK6DoKe5gR1moS8es602pBpFcsSUyyFBIqRrpR38,742
|
|
36
|
+
ssapling/interaction/hosting.py,sha256=slKOvgEmEHW1FTOt0m4i7ZSeTqhpjQSjVAUIUZFOYNA,11046
|
|
37
|
+
ssapling/models/__init__.py,sha256=l8Bn9JfJLvlkLHM7uYsTWItg3wskvfGAiGyDfX37EEk,1052
|
|
38
|
+
ssapling/models/buffering.py,sha256=KiM6ea0fHWiIcJBSdNBLGnTYu91wF1-ksSo3uVh4KDw,8278
|
|
39
|
+
ssapling/models/contracts.py,sha256=mK3F3jm45TpcH5tM5UsVoHlyxFAQ27AeeajCAU37NEA,6989
|
|
40
|
+
ssapling/models/errors.py,sha256=QHdH0rCFWUXPrLAeJALYjQMqaqM4H6kHx21Q3aYVMHU,998
|
|
41
|
+
ssapling/models/types.py,sha256=ikABZatBxfRFWiq5Op9BNTTJl2LicBQ8usQrbuzttUY,2377
|
|
42
|
+
ssapling/tasks/__init__.py,sha256=po7FuDtbc0MI6T_1k9ECCvoXTABGn2aAptFmLwdnrcs,1158
|
|
43
|
+
ssapling/tasks/contracts.py,sha256=M_aQBsDQMsUnrJ2STpWd4oGD8gFx9L1scPJ9T3bskCs,4787
|
|
44
|
+
ssapling/tasks/errors.py,sha256=u-5v3BsGsDIJQv5nhRd4BhkhYvxFSPuibVIu7Y9uHVM,1221
|
|
45
|
+
ssapling/tasks/types.py,sha256=2A4MhglxNgHMBcIcI2OvzfPM2YAvEW1U51xfQfuV1_A,7425
|
|
46
|
+
ssapling/teachers/__init__.py,sha256=rWLn0qRkJlWjGnUvLjlIQJUeHiiADEQECkL_AXGSc0Q,984
|
|
47
|
+
ssapling/teachers/contracts.py,sha256=jSPzPuhSRIaXjHsJrkCpcifonEsz5GrJCH27qhtLGBM,6110
|
|
48
|
+
ssapling/teachers/errors.py,sha256=BA8oXtO7Bq63kjEutc7_mPNU1CkhNonKPpOdPCBap7w,2917
|
|
49
|
+
ssapling/teachers/runner.py,sha256=33Nwim2UGC27Lbnk-1Huj5Kbqt1zFRdrsnK8PSGTskk,6661
|
|
50
|
+
ssapling/teachers/types.py,sha256=kj7QZ-Moq52XpPvgIAMPWaoRiFQ33qp-fhxHSBlG4Zg,8066
|
|
51
|
+
ssapling/train/__init__.py,sha256=YVPJ72TA0SZfBvwwKpMfg-UBMgCyjRZOiCEZegbIs1w,949
|
|
52
|
+
ssapling/train/components.py,sha256=qUywtqjnPJP5twnHPEM06d3pbFb0Io26NxBtJEpUdXs,7248
|
|
53
|
+
ssapling/train/context.py,sha256=KzCj5mLV02RXMoPt-QtRwHa4dhVoE7UeAufuTm2C_VE,6857
|
|
54
|
+
ssapling/train/errors.py,sha256=IGHa-BXvy7uGruxR3Jmh1Kxt4DdiL4FcRukmk_EXRx4,848
|
|
55
|
+
ssapling/train/procedure.py,sha256=R9oQoY7qwJ61rLTMTh18ugBcZtWK3ehIgqFooz-w9a8,11972
|
|
56
|
+
ssapling/train/runner.py,sha256=oFfBfOoZtTARxY2lw2UHoYONRyfyUV9YV8FXseaPgSA,17689
|
|
57
|
+
ssapling/train/stages.py,sha256=ZtaGSIlyEr4T4N07ZlqnmdGJy2Ox_Xh-BcAJI26otks,18098
|
|
58
|
+
ssapling-0.1.0.dist-info/METADATA,sha256=XVJ6Kk0jBZbotWdBYsjnZ-Vpebnka9uE02vrveXhYYc,5058
|
|
59
|
+
ssapling-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
60
|
+
ssapling-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
61
|
+
ssapling-0.1.0.dist-info/RECORD,,
|