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,181 @@
1
+ """The model contract, and the checks consumers make before using a model.
2
+
3
+ A model acts in one of two ways. The simple way is ``act(observations)``,
4
+ which returns an output. The buffered way is ``perceive(observations)`` to
5
+ put input in and ``poll()`` to read output, so a model can take as long as it
6
+ needs in between. ``as_buffered`` gives an act-only model the buffered
7
+ interface, so simple models never deal with buffers.
8
+
9
+ Everything else is optional, and a model that leaves it out simply does not
10
+ have it: episode resets, persistent state, an evaluation flag, learning
11
+ operations, learning signals, and descriptions of what it handles. Every
12
+ method may be ``def`` or ``async def``. These are structural protocols: a
13
+ downstream model implements them and inherits from nothing.
14
+
15
+ Consumers check before using an optional part::
16
+
17
+ from ssapling import models
18
+
19
+ if models.supports(model, "consolidate"):
20
+ stats = model.learn("consolidate", limits=limits)
21
+ models.check_descriptions(model, observations=..., actions=...)
22
+ """
23
+
24
+ from collections.abc import Awaitable, Mapping
25
+ from typing import Any, Protocol
26
+
27
+ from ..core._declarations import name_of, names
28
+ from .errors import DescriptionMismatchError
29
+ from .types import DescriptionKind, DescriptionMismatch, Refusal
30
+
31
+ __all__ = [
32
+ "ActModel",
33
+ "BufferedModel",
34
+ "Model",
35
+ "check_descriptions",
36
+ "filter_signals",
37
+ "supports",
38
+ ]
39
+
40
+
41
+ class ActModel(Protocol):
42
+ """A model that maps observations to an output in one call.
43
+
44
+ During interaction, observations become actions; in static solving,
45
+ inputs become predictions.
46
+ """
47
+
48
+ def act(self, observations: Any) -> Any:
49
+ """Return the output for ``observations``. May be ``async def``."""
50
+ ...
51
+
52
+
53
+ class BufferedModel(Protocol):
54
+ """A model that receives input and gives output separately, through buffers.
55
+
56
+ What happens in between is the model's own business. It may process in
57
+ the background, or offer ``advance()``, which does one internal step of
58
+ processing, so that runs in simulated time are reproducible.
59
+ """
60
+
61
+ def perceive(self, observations: Any) -> Awaitable[None] | None:
62
+ """Put ``observations`` in the input buffer, and return without waiting for output."""
63
+ ...
64
+
65
+ def poll(self) -> Any:
66
+ """Read the next output from the output buffer, or ``NOTHING`` if none is ready."""
67
+ ...
68
+
69
+
70
+ Model = ActModel | BufferedModel
71
+ """Any model: act-only or buffered."""
72
+
73
+
74
+ def supports(model: object, operation: str) -> bool:
75
+ """Whether ``model`` supports the learning operation ``operation``.
76
+
77
+ A model lists its learning operations in ``learning_operations``, such
78
+ as ``{"learn_from_batch", "consolidate"}``, and performs them with
79
+ ``learn(operation, **payload)``. Operations are an open set of names
80
+ chosen downstream. A model without ``learning_operations`` learns
81
+ nothing, which is allowed: a fixed rule or a frozen network is a model.
82
+
83
+ Raises:
84
+ TypeError: ``learning_operations`` is not a collection of names (a
85
+ single string is rejected), or the model lists operations but has
86
+ no ``learn`` method.
87
+ """
88
+ if not isinstance(operation, str):
89
+ raise TypeError(f"an operation is a name, got {operation!r}")
90
+ return operation in _learning_operations(model)
91
+
92
+
93
+ def filter_signals(model: object, signals: Mapping[str, Any]) -> dict[str, Any]:
94
+ """The learning signals ``model`` declares it uses, out of ``signals``; nothing else.
95
+
96
+ A model declares its signals by name in ``signals``, such as
97
+ ``{"reward", "supervision"}``. Only those are passed on, so, for example,
98
+ teacher feedback never reaches a model as a reward unless it asks for
99
+ it. A model that declares no signals receives none.
100
+
101
+ Raises:
102
+ TypeError: ``signals`` is not a mapping, or the model's ``signals``
103
+ are not a collection of names.
104
+ """
105
+ if not isinstance(signals, Mapping):
106
+ raise TypeError(f"signals must be a mapping of names to values, got {signals!r}")
107
+ declared = getattr(model, "signals", None)
108
+ used = (
109
+ set(names(declared, f"{name_of(model)}.signals", example="('reward',)"))
110
+ if declared is not None
111
+ else set()
112
+ )
113
+ return {name: value for name, value in signals.items() if name in used}
114
+
115
+
116
+ def check_descriptions(
117
+ model: object,
118
+ *,
119
+ observations: Any = None,
120
+ actions: Any = None,
121
+ participant: str | None = None,
122
+ ) -> None:
123
+ """Check that ``model`` handles an environment's observations and actions.
124
+
125
+ Pass the environment's descriptions for the participant the model
126
+ controls, as the environment reports them, or ``None`` where it gives
127
+ none. SSAPling does not interpret them. For each kind that both sides
128
+ describe:
129
+
130
+ - If the model has ``accepts_description(kind, description)``, it decides:
131
+ true accepts; false, or a ``Refusal`` saying why, refuses.
132
+ - Otherwise its ``observation_description`` or ``action_description``
133
+ must equal the environment's.
134
+
135
+ Where either side gives no description there is nothing to compare, so
136
+ nothing is checked.
137
+
138
+ Raises:
139
+ DescriptionMismatchError: The model cannot handle a description. The
140
+ error lists every mismatch.
141
+ """
142
+ given: dict[DescriptionKind, Any] = {"observation": observations, "action": actions}
143
+ accepts = getattr(model, "accepts_description", None)
144
+ if accepts is not None and not callable(accepts):
145
+ raise TypeError(
146
+ f"{name_of(model)}.accepts_description must be a method taking a kind and a "
147
+ f"description, got {accepts!r}"
148
+ )
149
+ mismatches = []
150
+ for kind, description in given.items():
151
+ if description is None:
152
+ continue
153
+ if accepts is not None:
154
+ answer = accepts(kind, description)
155
+ if not answer:
156
+ reason = answer.reason if isinstance(answer, Refusal) else None
157
+ mismatches.append(DescriptionMismatch(kind, description, reason=reason))
158
+ continue
159
+ handled = getattr(model, f"{kind}_description", None)
160
+ if handled is not None and handled != description:
161
+ mismatches.append(DescriptionMismatch(kind, description, handled))
162
+ if mismatches:
163
+ raise DescriptionMismatchError(name_of(model), mismatches, participant=participant)
164
+
165
+
166
+ # Reading a model's declarations
167
+
168
+
169
+ def _learning_operations(model: object) -> frozenset[str]:
170
+ declared = getattr(model, "learning_operations", None)
171
+ if declared is None:
172
+ return frozenset()
173
+ operations = frozenset(
174
+ names(declared, f"{name_of(model)}.learning_operations", example="('consolidate',)")
175
+ )
176
+ if operations and not callable(getattr(model, "learn", None)):
177
+ raise TypeError(
178
+ f"{name_of(model)} lists learning operations but has no learn method; "
179
+ "a model performs them with learn(operation, **payload)"
180
+ )
181
+ return operations
@@ -0,0 +1,27 @@
1
+ """Errors specific to models."""
2
+
3
+ from collections.abc import Iterable
4
+
5
+ from ..core.errors import SSAPlingError
6
+ from .types import DescriptionMismatch
7
+
8
+
9
+ class DescriptionMismatchError(SSAPlingError, ValueError):
10
+ """A model cannot handle an environment's observations or actions.
11
+
12
+ Attributes:
13
+ model: The model's class name.
14
+ participant: The participant the model was checked for, or ``None``.
15
+ mismatches: Every mismatch found, not just the first.
16
+ """
17
+
18
+ def __init__(
19
+ self, model: str, mismatches: Iterable[DescriptionMismatch], *, participant: str | None
20
+ ) -> None:
21
+ self.model = model
22
+ self.participant = participant
23
+ self.mismatches = tuple(mismatches)
24
+ role = f" as participant {participant!r}" if participant else ""
25
+ lines = [f"Model {model} cannot handle the environment's descriptions{role}:"]
26
+ lines += [str(mismatch) for mismatch in self.mismatches]
27
+ super().__init__("\n - ".join(lines))
@@ -0,0 +1,75 @@
1
+ """Small types of the Models area: the "no output yet" marker, a description mismatch, and a
2
+ model's refusal of a description."""
3
+
4
+ import enum
5
+ from dataclasses import dataclass
6
+ from typing import Any, Literal
7
+
8
+ __all__ = ["NOTHING", "DescriptionKind", "DescriptionMismatch", "Nothing", "Refusal"]
9
+
10
+
11
+ class Nothing(enum.Enum):
12
+ """The type of ``NOTHING``, which ``poll()`` returns when no output is ready."""
13
+
14
+ NOTHING = "NOTHING"
15
+
16
+ def __repr__(self) -> str:
17
+ return "NOTHING"
18
+
19
+
20
+ NOTHING = Nothing.NOTHING
21
+ """What ``poll()`` returns when no output is ready.
22
+
23
+ It is not ``None``, because ``None`` can be a real output. Compare with
24
+ ``is``: ``if output is NOTHING``. It is an enum member, so it stays the same
25
+ object when sent to or from another process.
26
+ """
27
+
28
+
29
+ DescriptionKind = Literal["observation", "action"]
30
+ """Which description: of the observations a model receives, or of the actions it gives."""
31
+
32
+
33
+ @dataclass(frozen=True, slots=True)
34
+ class DescriptionMismatch:
35
+ """One description a model cannot handle.
36
+
37
+ Attributes:
38
+ kind: ``"observation"`` or ``"action"``.
39
+ given: The environment's description.
40
+ handled: The model's own description, or ``None`` when the model
41
+ decided through ``accepts_description`` instead.
42
+ reason: Why the model refused, when its ``accepts_description``
43
+ answered with a ``Refusal``; otherwise ``None``.
44
+ """
45
+
46
+ kind: DescriptionKind
47
+ given: Any
48
+ handled: Any = None
49
+ reason: str | None = None
50
+
51
+ def __str__(self) -> str:
52
+ if self.handled is None:
53
+ refused = f"{self.kind}s: the model does not accept {self.given!r}"
54
+ return refused if self.reason is None else f"{refused}: {self.reason}"
55
+ return (
56
+ f"{self.kind}s: the model handles {self.handled!r}, "
57
+ f"the environment gives {self.given!r}"
58
+ )
59
+
60
+
61
+ @dataclass(frozen=True, slots=True)
62
+ class Refusal:
63
+ """What ``accepts_description`` may answer instead of ``False``: a
64
+ refusal that says why, such as which field the model reads and the
65
+ environment doesn't give. It is false, so code that reads the answer as
66
+ a bool still reads a refusal; ``check_descriptions`` keeps the reason.
67
+
68
+ Attributes:
69
+ reason: Why the model refuses the description.
70
+ """
71
+
72
+ reason: str
73
+
74
+ def __bool__(self) -> bool:
75
+ return False
ssapling/py.typed ADDED
File without changes
ssapling/registries.py ADDED
@@ -0,0 +1,37 @@
1
+ """Every registry in one place.
2
+
3
+ Each area owns its registry (``ssapling.tasks.registry`` and so on); this
4
+ module collects them so a downstream package can register everything from
5
+ one import::
6
+
7
+ from ssapling import registries as r
8
+
9
+ def register_components():
10
+ r.tasks.register("addition", AdditionTask)
11
+ r.teachers.register("digit_tutor", DigitTutor)
12
+ r.models.register("lookup", LookupModel)
13
+
14
+ More registries are added here as their areas are built.
15
+ """
16
+
17
+ from .data import codecs, collators, samplers
18
+ from .environments import registry as environments
19
+ from .evaluate import aggregators, assessments, measurements
20
+ from .models import registry as models
21
+ from .tasks import registry as tasks
22
+ from .teachers import registry as teachers
23
+ from .train import stages
24
+
25
+ __all__ = [
26
+ "aggregators",
27
+ "assessments",
28
+ "codecs",
29
+ "collators",
30
+ "environments",
31
+ "measurements",
32
+ "models",
33
+ "samplers",
34
+ "stages",
35
+ "tasks",
36
+ "teachers",
37
+ ]
@@ -0,0 +1,49 @@
1
+ """SSAPling tasks.
2
+
3
+ Responsibility: Problem definitions: instances, references, scoring, and
4
+ optional teaching resources.
5
+
6
+ Not its responsibility: Sampling, collections, streaming, storage, running
7
+ episodes.
8
+
9
+ May import: core. Enforced by tests/test_layering.py.
10
+ """
11
+
12
+ from collections.abc import Callable
13
+
14
+ from ..core import Registry
15
+ from .contracts import (
16
+ FEATURES,
17
+ EnumeratedTask,
18
+ GeneratedTask,
19
+ PartialChecker,
20
+ Task,
21
+ TeachingResourceProvider,
22
+ supports,
23
+ teaching_resource,
24
+ teaching_resources,
25
+ )
26
+ from .errors import MissingTeachingResourceError, UnknownInstanceError
27
+ from .types import Instance, PartialReport, Score, ScoreStatus
28
+
29
+ registry: Registry[Callable[..., Task]] = Registry("task")
30
+ """Registered tasks. Also available as ``ssapling.registries.tasks``."""
31
+
32
+ __all__ = [
33
+ "FEATURES",
34
+ "EnumeratedTask",
35
+ "GeneratedTask",
36
+ "Instance",
37
+ "MissingTeachingResourceError",
38
+ "PartialChecker",
39
+ "PartialReport",
40
+ "Score",
41
+ "ScoreStatus",
42
+ "Task",
43
+ "TeachingResourceProvider",
44
+ "UnknownInstanceError",
45
+ "registry",
46
+ "supports",
47
+ "teaching_resource",
48
+ "teaching_resources",
49
+ ]
@@ -0,0 +1,137 @@
1
+ """The task contract, its optional features, and helpers for consumers.
2
+
3
+ A task is any object with a ``score`` method. It becomes a *generated* task by
4
+ also offering ``generate``, an *enumerated* task by offering ``ids`` and
5
+ ``get``, and may offer ``check_partial`` and ``teaching_resources``. These are
6
+ structural protocols: a downstream task implements the methods and inherits
7
+ from nothing.
8
+
9
+ Consumers check a feature before using it::
10
+
11
+ from ssapling import tasks
12
+
13
+ if tasks.supports(task, "check_partial"):
14
+ report = task.check_partial(instance, state)
15
+ """
16
+
17
+ from collections.abc import Mapping, Sequence
18
+ from typing import Any, Protocol, cast
19
+
20
+ from ..core._declarations import has_feature
21
+ from .errors import MissingTeachingResourceError
22
+ from .types import Instance, PartialReport, Score
23
+
24
+ __all__ = [
25
+ "FEATURES",
26
+ "EnumeratedTask",
27
+ "GeneratedTask",
28
+ "PartialChecker",
29
+ "Task",
30
+ "TeachingResourceProvider",
31
+ "supports",
32
+ "teaching_resource",
33
+ "teaching_resources",
34
+ ]
35
+
36
+
37
+ class Task(Protocol):
38
+ """What every task provides: a judgement of one outcome of one instance."""
39
+
40
+ def score(self, instance: Instance, outcome: Any) -> Score:
41
+ """Score ``outcome``, one attempt's result, against ``instance``.
42
+
43
+ Return ``Score.local`` when the task can judge it, ``Score.external``
44
+ when a service reported it, and ``Score.unavailable`` otherwise, for
45
+ example when the reference is hidden. Never guess.
46
+ """
47
+ ...
48
+
49
+
50
+ class GeneratedTask(Task, Protocol):
51
+ """A task that makes instances from task-defined parameters and a seed."""
52
+
53
+ def generate(self, *, params: Mapping[str, Any] | None = None, seed: int) -> Instance:
54
+ """Make one instance. The same ``params`` and ``seed`` must give an equal instance."""
55
+ ...
56
+
57
+
58
+ class EnumeratedTask(Task, Protocol):
59
+ """A task with a fixed set of instances, each with an id."""
60
+
61
+ def ids(self) -> Sequence[str]:
62
+ """Every instance id, in a stable order."""
63
+ ...
64
+
65
+ def get(self, instance_id: str) -> Instance:
66
+ """The instance with that id.
67
+
68
+ Raises:
69
+ UnknownInstanceError: No instance has that id.
70
+ """
71
+ ...
72
+
73
+
74
+ class PartialChecker(Task, Protocol):
75
+ """A task that can judge an intermediate state (feature ``"check_partial"``)."""
76
+
77
+ def check_partial(self, instance: Instance, state: Any) -> PartialReport:
78
+ """Judge ``state``, a task-defined partial solution of ``instance``."""
79
+ ...
80
+
81
+
82
+ class TeachingResourceProvider(Task, Protocol):
83
+ """A task that offers task-level material for teachers (feature ``"teaching_resources"``)."""
84
+
85
+ def teaching_resources(self) -> Mapping[str, Any]:
86
+ """Resources keyed by name, such as a worked example or a solving procedure."""
87
+ ...
88
+
89
+
90
+ FEATURES: Mapping[str, tuple[str, ...]] = {
91
+ "generate": ("generate",),
92
+ "enumerate": ("ids", "get"),
93
+ "check_partial": ("check_partial",),
94
+ "teaching_resources": ("teaching_resources",),
95
+ }
96
+ """The optional features of a task, each with the methods it needs."""
97
+
98
+
99
+ def supports(task: object, feature: str) -> bool:
100
+ """Whether ``task`` offers ``feature``: one of ``FEATURES``.
101
+
102
+ A task offers a feature when it has every method the feature needs and,
103
+ if it defines a ``supports(feature)`` method of its own, that method
104
+ agrees. So a task declares a feature just by implementing it, and can
105
+ switch off a feature its class implements (for example when a setting
106
+ turns it off) by answering ``False`` from its own ``supports``.
107
+
108
+ A task's own ``supports`` only switches features off: it answers
109
+ ``False`` for those and ``True`` for every other feature. It must not
110
+ call this function, because this function calls it.
111
+
112
+ Raises:
113
+ ValueError: ``feature`` is not a task feature. That is a mistake in
114
+ the calling code, not something a task can answer.
115
+ TypeError: The task has a ``supports`` attribute that is not a method.
116
+ """
117
+ return has_feature(task, feature, FEATURES, word="feature", words="features")
118
+
119
+
120
+ def teaching_resources(task: object) -> dict[str, Any]:
121
+ """The task's teaching resources by name, or an empty dict if it offers none."""
122
+ if not supports(task, "teaching_resources"):
123
+ return {}
124
+ return dict(cast(TeachingResourceProvider, task).teaching_resources())
125
+
126
+
127
+ def teaching_resource(task: object, name: str) -> Any:
128
+ """One teaching resource of ``task``.
129
+
130
+ Raises:
131
+ MissingTeachingResourceError: The task offers no resource named
132
+ ``name``. The error lists the resources it does offer.
133
+ """
134
+ resources = teaching_resources(task)
135
+ if name not in resources:
136
+ raise MissingTeachingResourceError(name, resources)
137
+ return resources[name]
@@ -0,0 +1,37 @@
1
+ """Errors specific to tasks."""
2
+
3
+ from collections.abc import Iterable
4
+
5
+ from ..core.errors import SSAPlingError
6
+
7
+
8
+ class UnknownInstanceError(SSAPlingError, LookupError):
9
+ """An enumerated task has no instance with the requested id.
10
+
11
+ Attributes:
12
+ instance_id: The id that was requested.
13
+ """
14
+
15
+ def __init__(self, instance_id: str, *, task: str | None = None) -> None:
16
+ self.instance_id = instance_id
17
+ where = f" in task {task!r}" if task else ""
18
+ super().__init__(f"No instance {instance_id!r}{where}.")
19
+
20
+
21
+ class MissingTeachingResourceError(SSAPlingError, LookupError):
22
+ """A teaching resource was requested that the task does not offer.
23
+
24
+ Attributes:
25
+ name: The requested resource.
26
+ available: The names of the resources the task does offer.
27
+ """
28
+
29
+ def __init__(self, name: str, available: Iterable[str]) -> None:
30
+ self.name = name
31
+ self.available = tuple(sorted(available))
32
+ offered = (
33
+ f"it offers: {', '.join(repr(n) for n in self.available)}"
34
+ if self.available
35
+ else "it offers no teaching resources"
36
+ )
37
+ super().__init__(f"The task has no teaching resource {name!r}; {offered}.")