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,178 @@
1
+ """The result types of the Teachers area: a request, a response, and the response's status.
2
+
3
+ Environments and Data may import this module, and only this one, from
4
+ ``teachers``: a transition result can report teacher responses, and a record
5
+ step holds them. So it holds plain data and no teacher behaviour.
6
+ """
7
+
8
+ import dataclasses
9
+ from collections.abc import Mapping
10
+ from dataclasses import dataclass, field
11
+ from typing import Any, Literal
12
+
13
+ from ..core._declarations import check_identifier, check_int, keyed
14
+
15
+ __all__ = ["ResponseStatus", "TeacherRequest", "TeacherResponse"]
16
+
17
+
18
+ @dataclass(frozen=True, slots=True, kw_only=True)
19
+ class TeacherRequest:
20
+ """A request for a teacher's help, such as a review of a proposed action.
21
+
22
+ Attributes:
23
+ id: Identifies the request, so that its response can be matched to it.
24
+ operation: What is asked, such as ``"review_action"``. Each teacher
25
+ lists the operations it supports; the names are downstream choices.
26
+ context: What the teacher may use, keyed by name: for example the
27
+ instance, the current observation, or a partial answer. It need
28
+ not match what the student sees; the coordinating code decides
29
+ what goes in.
30
+ proposals: Proposed actions for the teacher to consider, keyed by
31
+ agent id.
32
+ episode: For live interaction, the episode the request belongs to.
33
+ participant: For live interaction, the agent the request concerns.
34
+ step: For live interaction, the environment step, counting from 0.
35
+
36
+ The request keeps its own copy of ``context`` and ``proposals``, made when
37
+ it is created, so a teacher that answers late still reads the state it
38
+ was asked about. Their values are treated as read-only: pass values that
39
+ will not change afterwards, such as a copy of a buffer the environment
40
+ reuses.
41
+ """
42
+
43
+ id: str
44
+ operation: str
45
+ context: Mapping[str, Any] = field(default_factory=dict)
46
+ proposals: Mapping[str, Any] = field(default_factory=dict)
47
+ episode: str | None = None
48
+ participant: str | None = None
49
+ step: int | None = None
50
+
51
+ def __post_init__(self) -> None:
52
+ check_identifier(self.id, "a request id")
53
+ check_identifier(self.operation, "an operation")
54
+ object.__setattr__(self, "context", keyed(self.context, "context", "names"))
55
+ object.__setattr__(self, "proposals", keyed(self.proposals, "proposals", "agent ids"))
56
+ if self.episode is not None:
57
+ check_identifier(self.episode, "an episode id")
58
+ if self.participant is not None:
59
+ check_identifier(self.participant, "a participant id")
60
+ if self.step is not None:
61
+ check_int(self.step, "step", minimum=0)
62
+
63
+
64
+ ResponseStatus = Literal["answered", "abstained", "failed", "cancelled", "stale"]
65
+ """What became of a request.
66
+
67
+ ``answered``: the teacher answered; its contributions say how.
68
+ ``abstained``: the teacher chose not to contribute.
69
+ ``failed``: no answer, because the teacher raised an error or gave an invalid
70
+ response. ``cancelled``: no answer, because the request was cancelled first,
71
+ for example when no answer came in time. ``stale``: an answer that arrived
72
+ after the state it was about had moved on. Its contributions are kept for the
73
+ record but are never applied automatically.
74
+
75
+ Only an answered response is applied automatically. Every other status means
76
+ the teacher has not approved anything.
77
+ """
78
+
79
+ _STATUSES: tuple[ResponseStatus, ...] = ("answered", "abstained", "failed", "cancelled", "stale")
80
+ _HAVE_CONTRIBUTIONS: tuple[ResponseStatus, ...] = ("answered", "stale")
81
+
82
+
83
+ @dataclass(frozen=True, slots=True, kw_only=True)
84
+ class TeacherResponse:
85
+ """A teacher's response to one request.
86
+
87
+ Attributes:
88
+ request_id: The id of the request this responds to.
89
+ status: ``"answered"``, ``"abstained"``, ``"failed"``,
90
+ ``"cancelled"``, or ``"stale"`` (see ``ResponseStatus``).
91
+ contributions: What the teacher contributed, keyed by kind and then by
92
+ agent id, such as ``{"feedback": {"student": "Carry the 1."}}``.
93
+ Kinds are open-ended. Common ones are ``supervision`` (a target,
94
+ not a command), ``feedback`` (not a reward), ``intervention`` (a
95
+ change to an executed action, applied only where supported),
96
+ ``demonstration``, ``explanation``, and ``instances`` (proposed
97
+ practice problems). Only answered and stale responses have
98
+ contributions.
99
+ detail: Optional. For an answer, a teacher-defined extra such as its
100
+ cost; for any other status, the reason.
101
+
102
+ Build one with ``TeacherResponse.answered(request, contributions)``,
103
+ ``.abstained(request, reason)``, ``.failed(request, reason)``, or
104
+ ``.cancelled(request, reason)``. These copy the request's id, so the
105
+ response always matches its request.
106
+ """
107
+
108
+ request_id: str
109
+ status: ResponseStatus
110
+ contributions: Mapping[str, Mapping[str, Any]] = field(default_factory=dict)
111
+ detail: Any = None
112
+
113
+ def __post_init__(self) -> None:
114
+ check_identifier(self.request_id, "a request id")
115
+ if self.status not in _STATUSES:
116
+ allowed = ", ".join(repr(status) for status in _STATUSES)
117
+ raise ValueError(f"status must be one of {allowed}; got {self.status!r}")
118
+ contributions = keyed(self.contributions, "contributions", "kinds")
119
+ for kind, per_agent in contributions.items():
120
+ if not isinstance(per_agent, Mapping):
121
+ raise TypeError(
122
+ f"contributions[{kind!r}] must map agent ids to payloads, such as "
123
+ f"{{'student': ...}}, got {per_agent!r}"
124
+ )
125
+ contributions[kind] = keyed(per_agent, f"contributions[{kind!r}]", "agent ids")
126
+ if contributions and self.status not in _HAVE_CONTRIBUTIONS:
127
+ raise ValueError(
128
+ f"a response with status {self.status!r} has no contributions; "
129
+ "put the reason in detail"
130
+ )
131
+ object.__setattr__(self, "contributions", contributions)
132
+
133
+ @classmethod
134
+ def answered(
135
+ cls,
136
+ request: TeacherRequest,
137
+ contributions: Mapping[str, Mapping[str, Any]] | None = None,
138
+ *,
139
+ detail: Any = None,
140
+ ) -> "TeacherResponse":
141
+ """The teacher's answer to ``request``. ``contributions`` may be empty."""
142
+ return cls(
143
+ request_id=request.id,
144
+ status="answered",
145
+ contributions=contributions or {},
146
+ detail=detail,
147
+ )
148
+
149
+ @classmethod
150
+ def abstained(cls, request: TeacherRequest, reason: Any = None) -> "TeacherResponse":
151
+ """The teacher chose not to contribute to ``request``."""
152
+ return cls(request_id=request.id, status="abstained", detail=reason)
153
+
154
+ @classmethod
155
+ def failed(cls, request: TeacherRequest, reason: Any = None) -> "TeacherResponse":
156
+ """The teacher could not answer ``request``."""
157
+ return cls(request_id=request.id, status="failed", detail=reason)
158
+
159
+ @classmethod
160
+ def cancelled(cls, request: TeacherRequest, reason: Any = None) -> "TeacherResponse":
161
+ """``request`` was cancelled before an answer arrived."""
162
+ return cls(request_id=request.id, status="cancelled", detail=reason)
163
+
164
+ def as_stale(self) -> "TeacherResponse":
165
+ """This answer, marked as having arrived too late to apply.
166
+
167
+ The coordinating code calls this when an answer arrives after the
168
+ state it was about has moved on. The contributions are kept, so the
169
+ record shows what the teacher said, but they are never applied
170
+ automatically.
171
+
172
+ Raises:
173
+ ValueError: The response is not an answer. Other statuses have
174
+ nothing that could be applied, so they are recorded as they are.
175
+ """
176
+ if self.status != "answered":
177
+ raise ValueError(f"only an answered response can be marked stale, not {self.status!r}")
178
+ return dataclasses.replace(self, status="stale")
@@ -0,0 +1,43 @@
1
+ """SSAPling train.
2
+
3
+ Responsibility: Composing and running training procedures from registered,
4
+ user-extensible stages: interaction, learning, checkpointing, and monitoring;
5
+ run seeds, saved settings, and outputs.
6
+
7
+ Not its responsibility: Scoring definitions and final assessment.
8
+
9
+ May import: everything. Enforced by tests/test_layering.py.
10
+ """
11
+
12
+ from .context import COUNTERS, Published, RunContext, derive_seed
13
+ from .errors import ProcedureStuckError
14
+ from .procedure import (
15
+ Condition,
16
+ Controller,
17
+ Entry,
18
+ Every,
19
+ FixedController,
20
+ Procedure,
21
+ ReplayController,
22
+ )
23
+ from .runner import Runner
24
+ from .stages import Stage, learn, stages
25
+
26
+ __all__ = [
27
+ "COUNTERS",
28
+ "Condition",
29
+ "Controller",
30
+ "Entry",
31
+ "Every",
32
+ "FixedController",
33
+ "Procedure",
34
+ "ProcedureStuckError",
35
+ "Published",
36
+ "ReplayController",
37
+ "RunContext",
38
+ "Runner",
39
+ "Stage",
40
+ "derive_seed",
41
+ "learn",
42
+ "stages",
43
+ ]
@@ -0,0 +1,194 @@
1
+ """The components a run builds from its settings: each from a registry, or the run's collections.
2
+
3
+ A run file lists them under ``components``, by role, in the order they are
4
+ built::
5
+
6
+ components:
7
+ task: {kind: tasks, name: addition, settings: {max_digits: 3}}
8
+ uniform: {kind: samplers, name: uniform, uses: {source: task}}
9
+ collections:
10
+ kind: collections
11
+ settings:
12
+ source: task
13
+ build: {validation: {sampler: uniform, size: 100, seed: 1}}
14
+ model: {kind: models, name: lookup}
15
+ """
16
+
17
+ from collections.abc import Mapping
18
+ from dataclasses import dataclass
19
+ from typing import Any, Literal
20
+
21
+ from ..core import ConfigError, Problem, Registry, UnknownComponentError, setting, validate_settings
22
+ from ..core._declarations import takes
23
+ from ..core._text import join_path
24
+ from ..data import Collections, collators, samplers
25
+ from ..environments import registry as environments
26
+ from ..evaluate import assessments
27
+ from ..models import registry as models
28
+ from ..tasks import registry as tasks
29
+ from ..teachers import registry as teachers
30
+ from .context import derive_seed
31
+
32
+ __all__ = ["CollectionSettings", "CollectionsSettings", "ComponentEntry"]
33
+
34
+ Kind = Literal[
35
+ "tasks",
36
+ "teachers",
37
+ "models",
38
+ "environments",
39
+ "samplers",
40
+ "collators",
41
+ "assessments",
42
+ "collections",
43
+ ]
44
+
45
+ KINDS: Mapping[str, Registry[Any]] = {
46
+ "tasks": tasks,
47
+ "teachers": teachers,
48
+ "models": models,
49
+ "environments": environments,
50
+ "samplers": samplers,
51
+ "collators": collators,
52
+ "assessments": assessments,
53
+ }
54
+ """The registry each kind of component is built from, by its name in ``ssapling.registries``."""
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class ComponentEntry:
59
+ """One component a run builds: a registered component, or the run's collections."""
60
+
61
+ kind: Kind = setting(
62
+ description=(
63
+ "Where it comes from: a registry, as named in ssapling.registries, or "
64
+ "'collections', for collections drawn from a source."
65
+ )
66
+ )
67
+ name: str | None = setting(
68
+ None, min_length=1, description="Its registered name. Collections have none."
69
+ )
70
+ settings: dict[str, Any] = setting(default_factory=dict, description="Its settings.")
71
+ uses: dict[str, str] = setting(
72
+ default_factory=dict,
73
+ description=(
74
+ "What it is built with: for each parameter, the role of a component built before "
75
+ "it, such as {source: task}."
76
+ ),
77
+ )
78
+
79
+ def validate(self) -> None:
80
+ if self.kind == "collections":
81
+ if self.name is not None or self.uses:
82
+ raise ValueError(
83
+ "collections have no name or uses: their settings name their source and "
84
+ "samplers"
85
+ )
86
+ elif self.name is None:
87
+ raise ValueError(f"name the registered {self.kind[:-1]}")
88
+
89
+
90
+ @dataclass(frozen=True)
91
+ class CollectionSettings:
92
+ """One collection to build, as for ``Collections.build``."""
93
+
94
+ sampler: str = setting(min_length=1, description="The role of the sampler that draws it.")
95
+ size: int = setting(ge=0, description="How many instances.")
96
+ seed: int = setting(description="Seeds every draw.")
97
+ held_out: bool = setting(False, description="Serve it only for evaluation.")
98
+ where: dict[str, Any] = setting(
99
+ default_factory=dict, description="Descriptor values every instance must have."
100
+ )
101
+ max_draws: int = setting(
102
+ 1000, ge=1, description="How many draws in a row may be rejected before giving up."
103
+ )
104
+
105
+
106
+ @dataclass(frozen=True)
107
+ class CollectionsSettings:
108
+ """Settings for a run's collections."""
109
+
110
+ source: str = setting(
111
+ min_length=1, description="The role of the source they are drawn from, such as the task."
112
+ )
113
+ build: dict[str, CollectionSettings] = setting(
114
+ default_factory=dict, description="The collections, by name, built in order."
115
+ )
116
+
117
+
118
+ def check_components(
119
+ entries: Mapping[str, ComponentEntry], given: Mapping[str, Any]
120
+ ) -> list[Problem]:
121
+ """Every problem with ``entries``, which come after the components ``given``; builds nothing."""
122
+ problems: list[Problem] = []
123
+ roles = set(given)
124
+ for role, entry in entries.items():
125
+ path = f"components.{role}"
126
+ if role in given:
127
+ problems.append(Problem(path, f"{role!r} is given as a component already"))
128
+ try:
129
+ if entry.kind == "collections":
130
+ settings = validate_settings(CollectionsSettings, entry.settings)
131
+ uses = {"settings.source": settings.source} | {
132
+ f"settings.build.{name}.sampler": collection.sampler
133
+ for name, collection in settings.build.items()
134
+ }
135
+ else:
136
+ KINDS[entry.kind].validate(str(entry.name), entry.settings)
137
+ uses = {f"uses.{parameter}": used for parameter, used in entry.uses.items()}
138
+ except UnknownComponentError as error:
139
+ problems.append(Problem(f"{path}.name", str(error)))
140
+ except ConfigError as error:
141
+ where = f"{path}.settings"
142
+ problems += [Problem(join_path(where, p.path), p.message) for p in error.problems]
143
+ else:
144
+ problems += [
145
+ Problem(f"{path}.{where}", f"{used!r} is not a component built before it")
146
+ for where, used in uses.items()
147
+ if used not in roles
148
+ ]
149
+ roles.add(role)
150
+ return problems
151
+
152
+
153
+ def build_components(
154
+ entries: Mapping[str, ComponentEntry], components: dict[str, Any], *, seed: int
155
+ ) -> dict[str, int]:
156
+ """Build ``entries`` in order, adding each to ``components``; return the seeds given.
157
+
158
+ A component whose constructor takes ``seed`` is given one derived from
159
+ the root seed and its role (``component-<role>``).
160
+ """
161
+ seeds = {}
162
+ for role, entry in entries.items():
163
+ if entry.kind == "collections":
164
+ settings = validate_settings(CollectionsSettings, entry.settings)
165
+ components[role] = _collections(settings, components, entries)
166
+ continue
167
+ registry, name = KINDS[entry.kind], str(entry.name)
168
+ arguments = {parameter: components[used] for parameter, used in entry.uses.items()}
169
+ if takes(registry.get(name), "seed"):
170
+ arguments["seed"] = seeds[role] = derive_seed(seed, f"component-{role}")
171
+ components[role] = registry.create(name, entry.settings, **arguments)
172
+ return seeds
173
+
174
+
175
+ def _collections(
176
+ settings: CollectionsSettings,
177
+ components: Mapping[str, Any],
178
+ entries: Mapping[str, ComponentEntry],
179
+ ) -> Collections:
180
+ source = entries.get(settings.source) # its registered name makes provenance rebuildable
181
+ collections = Collections(
182
+ components[settings.source], source_name=source.name if source is not None else None
183
+ )
184
+ for name, collection in settings.build.items():
185
+ collections.build(
186
+ name,
187
+ sampler=components[collection.sampler],
188
+ size=collection.size,
189
+ seed=collection.seed,
190
+ held_out=collection.held_out,
191
+ where=collection.where or None,
192
+ max_draws=collection.max_draws,
193
+ )
194
+ return collections
@@ -0,0 +1,169 @@
1
+ """The run context: what the stages of a run share.
2
+
3
+ A stage never hands anything to another stage directly. It reads from the
4
+ run context and publishes values to it: the components built for the run,
5
+ the run's counters, its seeds, and a table of published values.
6
+ """
7
+
8
+ import random
9
+ import time
10
+ from collections.abc import Mapping
11
+ from dataclasses import dataclass
12
+ from typing import Any
13
+
14
+ from ..core._declarations import check_identifier
15
+ from ..core._plain import plain_copy
16
+ from ..core.errors import Problem
17
+
18
+ __all__ = ["COUNTERS", "Published", "RunContext"]
19
+
20
+ COUNTERS = ("episodes", "steps", "updates", "stages")
21
+ """The run's counters.
22
+
23
+ ``episodes`` and ``steps``: episodes run and environment steps taken.
24
+ ``updates``: calls to a learning operation. ``stages``: stages started.
25
+ """
26
+
27
+
28
+ @dataclass(frozen=True, slots=True)
29
+ class Published:
30
+ """A published value, stamped with the counters at which it was published.
31
+
32
+ Attributes:
33
+ value: The value: plain data.
34
+ counters: The run's counters when it was published.
35
+ """
36
+
37
+ value: Any
38
+ counters: Mapping[str, int]
39
+
40
+
41
+ class RunContext:
42
+ """What the stages of a run share.
43
+
44
+ Attributes:
45
+ components: The run's components, keyed by role, such as
46
+ ``"model"`` or ``"environment"``. ``"store"`` is the run's
47
+ store, if it has one.
48
+ counters: The counters in ``COUNTERS``, starting at 0. The stages
49
+ that do the work count it: the interact stage counts episodes
50
+ and steps, a learning stage counts updates.
51
+ values: The published values, keyed by name.
52
+ root_seed: The run's root seed, from which every other seed is
53
+ derived (see ``seed``).
54
+ controller: What decides the run's next stage; a checkpoint saves
55
+ its state.
56
+ session: 0 for a run as first started, and ``k`` once it has been
57
+ resumed ``k`` times (see ``output_name``).
58
+ decisions: Every decision the controller has made, in order, as
59
+ plain data: the stage and settings it chose, what it saw (the
60
+ counters, running time and published values, as
61
+ ``export_state`` gives them), and why it was refused, if it
62
+ was.
63
+ """
64
+
65
+ def __init__(
66
+ self, components: Mapping[str, Any], *, seed: int, controller: object = None
67
+ ) -> None:
68
+ self.components = dict(components)
69
+ self.counters = dict.fromkeys(COUNTERS, 0)
70
+ self.values: dict[str, Published] = {}
71
+ self.root_seed = seed
72
+ self.controller = controller
73
+ self.session = 0
74
+ self.decisions: list[dict[str, Any]] = []
75
+ self._started = time.monotonic()
76
+ self._before = 0.0 # seconds run before it was last resumed
77
+
78
+ @property
79
+ def seconds(self) -> float:
80
+ """Seconds the run has been running, across its resumptions."""
81
+ return self._before + time.monotonic() - self._started
82
+
83
+ def seed(self, name: str) -> int:
84
+ """The seed for ``name``, derived from the root seed.
85
+
86
+ The rule is fixed: the same root seed and name always give the same
87
+ seed, on every machine, and different names give unrelated seeds.
88
+ """
89
+ return derive_seed(self.root_seed, name)
90
+
91
+ def output_name(self, base: str) -> str:
92
+ """The name to write a record or document under: ``base``, or in a resumed run a new one.
93
+
94
+ A run resumes from its last checkpoint, and what it wrote after
95
+ that checkpoint is still in its store. So once resumed, it writes
96
+ under ``"resume-<session>/<base>"``, and replaces nothing.
97
+ """
98
+ return base if self.session == 0 else f"resume-{self.session}/{base}"
99
+
100
+ def export_state(self) -> dict[str, Any]:
101
+ """The counters, running time and published values, for a checkpoint."""
102
+ return {
103
+ "counters": dict(self.counters),
104
+ "seconds": self.seconds,
105
+ "values": {
106
+ name: {"value": published.value, "counters": dict(published.counters)}
107
+ for name, published in self.values.items()
108
+ },
109
+ }
110
+
111
+ def restore_state(self, state: Mapping[str, Any]) -> None:
112
+ """Return to what ``export_state`` saved."""
113
+ self.counters = dict(state["counters"])
114
+ self._before, self._started = state["seconds"], time.monotonic()
115
+ self.values = {
116
+ name: Published(saved["value"], saved["counters"])
117
+ for name, saved in state["values"].items()
118
+ }
119
+
120
+ def publish(self, name: str, value: Any) -> None:
121
+ """Publish ``value`` under ``name``, stamped with the current counters.
122
+
123
+ It replaces what was published under ``name`` before. Values are
124
+ plain data (``None``, booleans, numbers, strings, and lists and
125
+ string-keyed dicts of these), so they can be saved with a checkpoint
126
+ and shown to a controller.
127
+
128
+ Raises:
129
+ ValueError: ``name`` is empty or has a dot, which ``read`` uses
130
+ to look inside a value.
131
+ TypeError: Part of ``value`` is not plain.
132
+ """
133
+ check_identifier(name, "a value's name")
134
+ if "." in name:
135
+ raise ValueError(f"a value's name has no dots, which separate a path: {name!r}")
136
+ problems: list[Problem] = []
137
+ plain = plain_copy(value, name, problems)
138
+ if problems:
139
+ raise TypeError("published values are plain data: " + "; ".join(map(str, problems)))
140
+ self.values[name] = Published(plain, dict(self.counters))
141
+
142
+ def read(self, path: str) -> Any:
143
+ """The value published under a name, or inside one by a dotted path.
144
+
145
+ ``read("monitoring")`` is the whole value the assess stage published
146
+ for the assessment ``monitoring``, and
147
+ ``read("monitoring.accuracy")`` is one aggregate in it.
148
+
149
+ Raises:
150
+ LookupError: Nothing is published under the name, or the path
151
+ leads nowhere in its value.
152
+ """
153
+ name, *keys = path.split(".")
154
+ if name not in self.values:
155
+ published = ", ".join(repr(name) for name in self.values) or "none"
156
+ raise LookupError(f"nothing is published as {name!r}; published: {published}")
157
+ value = self.values[name].value
158
+ for depth, key in enumerate(keys):
159
+ if not isinstance(value, Mapping) or key not in value:
160
+ where = ".".join([name, *keys[:depth]])
161
+ has = ", ".join(map(repr, value)) if isinstance(value, Mapping) else "no keys"
162
+ raise LookupError(f"{where!r} has no {key!r}; it has {has}")
163
+ value = value[key]
164
+ return value
165
+
166
+
167
+ def derive_seed(root: int, name: str) -> int:
168
+ """The seed for ``name`` in a run with the root seed ``root``: see ``RunContext.seed``."""
169
+ return random.Random(f"{root}:{name}").getrandbits(32)
@@ -0,0 +1,24 @@
1
+ """Errors specific to train."""
2
+
3
+ from collections.abc import Mapping
4
+
5
+ from ..core.errors import SSAPlingError
6
+
7
+
8
+ class ProcedureStuckError(SSAPlingError, RuntimeError):
9
+ """Nothing in a fixed procedure can run, and its stop condition does not hold.
10
+
11
+ Raised instead of looping forever, after a whole pass through the list
12
+ in which no entry's trigger fired.
13
+
14
+ Attributes:
15
+ counters: The run's counters at that point.
16
+ """
17
+
18
+ def __init__(self, counters: Mapping[str, int]) -> None:
19
+ self.counters = dict(counters)
20
+ shown = ", ".join(f"{name} {count}" for name, count in self.counters.items())
21
+ super().__init__(
22
+ f"Nothing in the procedure can run: no entry's trigger fires, and the stop "
23
+ f"condition does not hold ({shown}). Check the triggers and the stop condition."
24
+ )