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.
Files changed (61) hide show
  1. ssapling/__init__.py +12 -0
  2. ssapling/core/__init__.py +53 -0
  3. ssapling/core/_declarations.py +139 -0
  4. ssapling/core/_execution.py +155 -0
  5. ssapling/core/_plain.py +37 -0
  6. ssapling/core/_text.py +42 -0
  7. ssapling/core/errors.py +175 -0
  8. ssapling/core/loading.py +205 -0
  9. ssapling/core/registry.py +345 -0
  10. ssapling/core/settings.py +698 -0
  11. ssapling/core/spec.py +98 -0
  12. ssapling/data/__init__.py +89 -0
  13. ssapling/data/_matching.py +22 -0
  14. ssapling/data/batching.py +166 -0
  15. ssapling/data/collections.py +335 -0
  16. ssapling/data/encoding.py +107 -0
  17. ssapling/data/errors.py +104 -0
  18. ssapling/data/provenance.py +94 -0
  19. ssapling/data/records.py +546 -0
  20. ssapling/data/sampling.py +339 -0
  21. ssapling/data/storage.py +569 -0
  22. ssapling/environments/__init__.py +43 -0
  23. ssapling/environments/contracts.py +168 -0
  24. ssapling/environments/errors.py +53 -0
  25. ssapling/environments/runner.py +153 -0
  26. ssapling/environments/types.py +173 -0
  27. ssapling/evaluate/__init__.py +40 -0
  28. ssapling/evaluate/aggregation.py +173 -0
  29. ssapling/evaluate/assessment.py +429 -0
  30. ssapling/evaluate/measurement.py +165 -0
  31. ssapling/interaction/__init__.py +24 -0
  32. ssapling/interaction/episode.py +713 -0
  33. ssapling/interaction/errors.py +21 -0
  34. ssapling/interaction/hosting.py +287 -0
  35. ssapling/models/__init__.py +44 -0
  36. ssapling/models/buffering.py +189 -0
  37. ssapling/models/contracts.py +181 -0
  38. ssapling/models/errors.py +27 -0
  39. ssapling/models/types.py +75 -0
  40. ssapling/py.typed +0 -0
  41. ssapling/registries.py +37 -0
  42. ssapling/tasks/__init__.py +49 -0
  43. ssapling/tasks/contracts.py +137 -0
  44. ssapling/tasks/errors.py +37 -0
  45. ssapling/tasks/types.py +172 -0
  46. ssapling/teachers/__init__.py +34 -0
  47. ssapling/teachers/contracts.py +145 -0
  48. ssapling/teachers/errors.py +80 -0
  49. ssapling/teachers/runner.py +142 -0
  50. ssapling/teachers/types.py +178 -0
  51. ssapling/train/__init__.py +43 -0
  52. ssapling/train/components.py +194 -0
  53. ssapling/train/context.py +169 -0
  54. ssapling/train/errors.py +24 -0
  55. ssapling/train/procedure.py +316 -0
  56. ssapling/train/runner.py +398 -0
  57. ssapling/train/stages.py +463 -0
  58. ssapling-0.1.0.dist-info/METADATA +113 -0
  59. ssapling-0.1.0.dist-info/RECORD +61 -0
  60. ssapling-0.1.0.dist-info/WHEEL +4 -0
  61. ssapling-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,398 @@
1
+ """The runner: builds a run, runs its procedure stage by stage until it stops, and resumes it."""
2
+
3
+ import logging
4
+ import os
5
+ import re
6
+ from collections.abc import Mapping
7
+ from typing import Any, cast
8
+
9
+ from ..core import (
10
+ ConfigError,
11
+ Problem,
12
+ UnknownComponentError,
13
+ load_config,
14
+ settings_to_dict,
15
+ validate_settings,
16
+ )
17
+ from ..core._declarations import check_int, name_of, names
18
+ from ..core._execution import Execution
19
+ from ..core._text import join_path
20
+ from ..data import RecordStore, Store
21
+ from .components import build_components, check_components
22
+ from .context import RunContext
23
+ from .procedure import Condition, Controller, Decision, Entry, FixedController, Procedure
24
+ from .stages import stages
25
+
26
+ __all__ = ["Runner"]
27
+
28
+ _log = logging.getLogger("ssapling.train")
29
+ _CHECKPOINT = re.compile(r"(?:resume-\d+/)?checkpoints/(\d+)")
30
+ _REFUSALS = 3
31
+ """Refused decisions in a row after which the run fails, with the last refusal."""
32
+
33
+
34
+ class Runner:
35
+ """Runs a procedure: builds its components, then runs what the controller decides, checked.
36
+
37
+ Example::
38
+
39
+ runner = Runner(
40
+ {
41
+ "procedure": [
42
+ {"stage": "interact", "settings": {"episodes": 32}},
43
+ {"stage": "learn_operation", "every": {"episodes": 500},
44
+ "settings": {"operation": "consolidate"}},
45
+ ],
46
+ "stop": {"episodes": 100000},
47
+ },
48
+ {"model": model, "environment": env, "sampler": sampler},
49
+ seed=7,
50
+ output="runs/baseline",
51
+ )
52
+ context = await runner.run()
53
+
54
+ runner = Runner.from_config("run.yaml", seed=7, output="runs/baseline")
55
+ runner = Runner.resume("runs/baseline") # from its last checkpoint
56
+
57
+ Args:
58
+ procedure: A ``Procedure``, or a mapping of its settings, such as
59
+ one read from a file. Its ``components`` are built when the run
60
+ starts. A mapping may leave out its ``procedure`` list when the
61
+ controller offers one, as ``controller.procedure()``: every entry
62
+ the controller can decide, which are then checked before the run.
63
+ components: Components given as they are, keyed by role, such as a
64
+ model built in Python, or a function. They are built before the
65
+ procedure's own, which can use them.
66
+ seed: The root seed: every seed in the run is derived from it.
67
+ output: Where the run writes: a directory for a ``RecordStore``,
68
+ or a ``Store``. It is the component ``"store"``. Records,
69
+ results, checkpoints and the run's settings go there.
70
+ controller: Decides what the run does next. By default, a
71
+ ``FixedController`` following the procedure's list. If a run with
72
+ a store ends in an error, the error's type and message are saved
73
+ with its decisions, as ``"error"``.
74
+
75
+ Raises:
76
+ ConfigError: The procedure's settings, or its components', are
77
+ invalid, listing every problem.
78
+ ValueError: A component is given as ``"store"``.
79
+ """
80
+
81
+ def __init__(
82
+ self,
83
+ procedure: Procedure | Mapping[str, Any],
84
+ components: Mapping[str, Any] | None = None,
85
+ *,
86
+ seed: int,
87
+ output: str | os.PathLike[str] | Store | None = None,
88
+ controller: Controller | None = None,
89
+ ) -> None:
90
+ offered = getattr(controller, "procedure", None)
91
+ if isinstance(procedure, Mapping) and "procedure" not in procedure and callable(offered):
92
+ procedure = {**procedure, "procedure": offered()} # checked before the run, as given
93
+ self.procedure = validate_settings(Procedure, procedure)
94
+ self.components = dict(components or {})
95
+ check_int(seed, "seed")
96
+ self.seed = seed
97
+ self.store = _store(output)
98
+ self.controller = controller
99
+ self._resuming = False
100
+ if "store" in self.components:
101
+ raise ValueError("the run's store is where it writes: give it as output=")
102
+ problems = check_components(self.procedure.components, self._given())
103
+ if problems:
104
+ raise ConfigError("procedure", problems)
105
+
106
+ @classmethod
107
+ def from_config(
108
+ cls,
109
+ path: str | os.PathLike[str],
110
+ *,
111
+ seed: int,
112
+ output: str | os.PathLike[str] | Store | None = None,
113
+ components: Mapping[str, Any] | None = None,
114
+ controller: Controller | None = None,
115
+ ) -> "Runner":
116
+ """A runner for the run file at ``path``: its components, procedure and stop condition.
117
+
118
+ Raises:
119
+ ConfigError: The file, or its settings, are invalid; the error
120
+ names the file.
121
+ """
122
+ try:
123
+ procedure = load_config(path)
124
+ return cls(procedure, components, seed=seed, output=output, controller=controller)
125
+ except ConfigError as error:
126
+ raise ConfigError(f"run file {path}", error.problems) from None
127
+
128
+ @classmethod
129
+ def resume(
130
+ cls,
131
+ output: str | os.PathLike[str] | Store,
132
+ *,
133
+ components: Mapping[str, Any] | None = None,
134
+ controller: Controller | None = None,
135
+ ) -> "Runner":
136
+ """A runner that continues the run written at ``output``, from its last checkpoint.
137
+
138
+ The run is rebuilt from the settings it saved. Components it was
139
+ given as they are, and a controller of its own, are given again.
140
+
141
+ Raises:
142
+ UnknownDocumentError: No run was written at ``output``.
143
+ ValueError: A component or controller the run was given is
144
+ missing.
145
+ """
146
+ store = _store(output)
147
+ assert store is not None
148
+ saved = store.load_document("run")
149
+ missing = sorted(set(saved["given"]) - set(components or {}))
150
+ if missing:
151
+ raise ValueError(f"give the run its components again: {', '.join(map(repr, missing))}")
152
+ if saved["controller"] is not None and controller is None:
153
+ raise ValueError(f"give the run its controller again, a {saved['controller']}")
154
+ runner = cls(
155
+ saved["procedure"], components, seed=saved["seed"], output=store, controller=controller
156
+ )
157
+ runner._resuming = True
158
+ return runner
159
+
160
+ async def run(self) -> RunContext:
161
+ """Run until the stop condition holds or the controller stops; return the run context.
162
+
163
+ First the procedure's components are built, in order. Then, before
164
+ any stage runs, every entry of the procedure is checked, and every
165
+ problem is reported together: unknown stages, invalid settings,
166
+ components a stage requires that the run does not have, a stage's
167
+ own ``check``, and values a stage or a condition reads that no
168
+ stage in the procedure publishes. A new run saves its settings in
169
+ its store; a resumed one restores its last checkpoint. Then, until
170
+ the stop condition holds, the controller decides, and its decision
171
+ is checked the same way (now against the values published so far)
172
+ and run. At the end, the components the run built are closed.
173
+
174
+ Raises:
175
+ ConfigError: The procedure, or a decision, cannot run.
176
+ ProcedureStuckError: Nothing in a fixed procedure can run.
177
+ ValueError: The store holds a run already, and this one is not
178
+ resumed.
179
+ Exception: A stage's own error, as itself.
180
+ """
181
+ components = self._given()
182
+ try:
183
+ seeds = build_components(self.procedure.components, components, seed=self.seed)
184
+ controller = self.controller or FixedController(self.procedure)
185
+ context = RunContext(components, seed=self.seed, controller=controller)
186
+ self._check(context)
187
+ if self._resuming:
188
+ await self._restore(context)
189
+ elif self.store is not None:
190
+ self._save_run(seeds)
191
+ ended: BaseException | None = None # the error that ended the run, if one did
192
+ try:
193
+ await self._loop(context, controller)
194
+ except BaseException as error:
195
+ ended = error
196
+ raise
197
+ finally: # how the run went, whatever ended it
198
+ if self.store is not None:
199
+ document: dict[str, Any] = {"decisions": context.decisions}
200
+ if ended is not None:
201
+ document["error"] = {"type": type(ended).__name__, "message": str(ended)}
202
+ self.store.save_document(context.output_name("decisions"), document)
203
+ return context
204
+ finally: # what the run built, it closes
205
+ for role in reversed(self.procedure.components):
206
+ close = getattr(components.get(role), "close", None)
207
+ if callable(close):
208
+ await Execution().call(close)
209
+
210
+ async def _loop(self, context: RunContext, controller: Controller) -> None:
211
+ refused, last = 0, None # decisions refused in a row, and why the last was
212
+ while not self.procedure.stop.holds(context):
213
+ decision: object = await Execution().call(controller.decide, context, last)
214
+ if decision is None:
215
+ _log.info("the controller stopped the run")
216
+ return
217
+ seen, entry = context.export_state(), None
218
+ try:
219
+ entry = validate_settings(Entry, cast(Decision, decision)) # checked here
220
+ stage = self._decided(entry, context)
221
+ except ConfigError as error:
222
+ refused, last = refused + 1, error
223
+ context.decisions.append(_logged(entry, seen, refused=str(error)))
224
+ _log.info("decision refused: %s", error)
225
+ if refused == _REFUSALS:
226
+ raise
227
+ continue
228
+ refused, last = 0, None
229
+ context.decisions.append(_logged(entry, seen, refused=None))
230
+ context.counters["stages"] += 1
231
+ _log.info("stage %d: %s", context.counters["stages"], entry.stage)
232
+ await Execution().call(stage.run, context)
233
+ _log.info("the stop condition holds")
234
+
235
+ def _decided(self, entry: Entry, context: RunContext) -> Any:
236
+ """Build the stage a decision names, if it can run now.
237
+
238
+ Raises:
239
+ ConfigError: It cannot: as for an entry of the procedure, or
240
+ because it reads a value that is not published yet.
241
+ """
242
+ stage, problems = self._prepare(entry, context, "")
243
+ unread = _declared(stage, "reads") - set(context.values) - _declared(stage, "publishes")
244
+ problems += [Problem("", f"reads {name!r}, which is not published") for name in unread]
245
+ if problems:
246
+ raise ConfigError(f"decision to run stage {entry.stage!r}", problems)
247
+ return stage
248
+
249
+ def _given(self) -> dict[str, Any]:
250
+ """The components given as they are, with the run's store."""
251
+ store = {} if self.store is None else {"store": self.store}
252
+ return {**self.components, **store}
253
+
254
+ def _save_run(self, seeds: Mapping[str, int]) -> None:
255
+ """Save what rebuilds the run: its settings, its seeds, and what it was given."""
256
+ assert self.store is not None
257
+ settings = {
258
+ "procedure": settings_to_dict(self.procedure),
259
+ "seed": self.seed,
260
+ "seeds": dict(seeds),
261
+ "given": sorted(self.components),
262
+ "controller": None if self.controller is None else name_of(self.controller),
263
+ }
264
+ try:
265
+ self.store.save_document("run", settings)
266
+ except ValueError as error:
267
+ error.add_note("Resume that run with Runner.resume, or give this one a new output.")
268
+ raise
269
+
270
+ async def _restore(self, context: RunContext) -> None:
271
+ """Continue from the last checkpoint, as a new session; or from the start, if none."""
272
+ assert self.store is not None
273
+ names = self.store.document_names()
274
+ context.session = 1 + sum(name.startswith("resumes/") for name in names)
275
+ checkpoint = _latest_checkpoint(names)
276
+ self.store.save_document(f"resumes/{context.session}", {"checkpoint": checkpoint})
277
+ if checkpoint is None:
278
+ _log.info("resuming from the start: the run has no checkpoint")
279
+ return
280
+ saved = self.store.load_document(checkpoint)
281
+ context.restore_state(saved["context"])
282
+ context.decisions = list(saved["decisions"])
283
+ for role, state in saved["components"].items():
284
+ await _put_back(context.components[role], state, repr(role))
285
+ if saved["controller"] is not None:
286
+ await _put_back(context.controller, saved["controller"], "the controller")
287
+ fresh = [role for role in context.components if role not in {*saved["components"], "store"}]
288
+ _log.info("resumed from %s", checkpoint)
289
+ if fresh:
290
+ _log.warning(
291
+ "These components do not export their state, so they start as built: %s",
292
+ ", ".join(fresh),
293
+ )
294
+
295
+ def _check(self, context: RunContext) -> None:
296
+ """Check every entry of the procedure before the run, reporting every problem."""
297
+ problems: list[Problem] = []
298
+ built = []
299
+ for index, entry in enumerate(self.procedure.procedure):
300
+ path = f"procedure[{index}]"
301
+ stage, found = self._prepare(entry, context, path)
302
+ problems += found
303
+ built.append((path, entry, stage))
304
+ published = {name for _, _, stage in built for name in _declared(stage, "publishes")}
305
+ readers: list[tuple[str, object]] = [] # what reads values, and where it is
306
+ for path, entry, stage in built:
307
+ readers += [(path, stage), (f"{path}.until.value", entry.until)]
308
+ readers += [(f"{path}.when.value", entry.when)]
309
+ readers += [("stop.value", self.procedure.stop)]
310
+ problems += [
311
+ Problem(path, f"reads {name!r}, which no stage in the procedure publishes")
312
+ for path, reader in readers
313
+ for name in sorted(_reads(reader) - published)
314
+ ]
315
+ if problems:
316
+ raise ConfigError("procedure", problems)
317
+
318
+ def _prepare(self, entry: Entry, context: RunContext, path: str) -> tuple[Any, list[Problem]]:
319
+ """Build ``entry``'s stage, and find what stops it running with the run's components.
320
+
321
+ Returns the stage (``None`` if it cannot be built) and the problems.
322
+ """
323
+ settings_path = join_path(path, "settings")
324
+ try:
325
+ stage = stages.create(entry.stage, entry.settings)
326
+ except UnknownComponentError as error:
327
+ return None, [Problem(join_path(path, "stage"), str(error))]
328
+ except ConfigError as error:
329
+ return None, [
330
+ Problem(join_path(settings_path, problem.path), problem.message)
331
+ for problem in error.problems
332
+ ]
333
+ problems = []
334
+ missing = [role for role in _declared(stage, "requires") if role not in context.components]
335
+ if missing:
336
+ have = ", ".join(map(repr, context.components)) or "none"
337
+ problems.append(
338
+ Problem(
339
+ path,
340
+ f"stage {entry.stage!r} requires {', '.join(map(repr, missing))}, which the "
341
+ f"run does not have (its components: {have})",
342
+ )
343
+ )
344
+ check = getattr(stage, "check", None)
345
+ if not missing and callable(check):
346
+ try:
347
+ check(context)
348
+ except ValueError as error:
349
+ problems.append(Problem(path, f"stage {entry.stage!r}: {error}"))
350
+ return stage, problems
351
+
352
+
353
+ def _logged(entry: Entry | None, seen: Mapping[str, Any], *, refused: str | None) -> dict[str, Any]:
354
+ """A decision as the run records it: the entry, what the controller saw, any refusal."""
355
+ return {
356
+ "stage": None if entry is None else entry.stage,
357
+ "settings": None if entry is None else entry.settings,
358
+ "seen": seen,
359
+ "refused": refused,
360
+ }
361
+
362
+
363
+ async def _put_back(owner: object, state: Any, what: str) -> None:
364
+ """Give ``owner`` back the state it saved."""
365
+ restore = getattr(owner, "restore_state", None)
366
+ if not callable(restore):
367
+ raise TypeError(f"{what} saved its state, but has no restore_state to take it back")
368
+ await Execution().call(restore, state)
369
+
370
+
371
+ def _store(output: str | os.PathLike[str] | Store | None) -> Store | None:
372
+ return RecordStore(output) if isinstance(output, str | os.PathLike) else output
373
+
374
+
375
+ def _latest_checkpoint(names: tuple[str, ...]) -> str | None:
376
+ """The checkpoint taken at the latest stage.
377
+
378
+ A resumed run continues from the latest checkpoint, so its own come at
379
+ later stages: the latest stage is the latest checkpoint, whichever
380
+ session took it.
381
+ """
382
+ found = [(int(match[1]), name) for name in names if (match := _CHECKPOINT.fullmatch(name))]
383
+ return max(found)[1] if found else None
384
+
385
+
386
+ def _declared(stage: object, what: str) -> set[str]:
387
+ """The names ``stage`` declares in ``what``: ``requires``, ``reads`` or ``publishes``."""
388
+ if stage is None:
389
+ return set()
390
+ declared = getattr(stage, what, ())
391
+ return set(names(declared, f"{name_of(stage)}.{what}", example="('model',)"))
392
+
393
+
394
+ def _reads(reader: object) -> set[str]:
395
+ """The values a stage or a condition reads."""
396
+ if isinstance(reader, Condition):
397
+ return set() if reader.reads is None else {reader.reads}
398
+ return _declared(reader, "reads")