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/core/spec.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Component specs: one ``{name, settings}`` entry, in Python or from a file."""
|
|
2
|
+
|
|
3
|
+
import difflib
|
|
4
|
+
from collections.abc import Mapping
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from ._text import join_path, show
|
|
9
|
+
from .errors import ConfigError, Problem
|
|
10
|
+
|
|
11
|
+
_KEYS = ("name", "settings")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True, slots=True)
|
|
15
|
+
class ComponentSpec:
|
|
16
|
+
"""Which registered component to build, and the settings to build it with.
|
|
17
|
+
|
|
18
|
+
This is SSAPling's format for one component entry. In YAML::
|
|
19
|
+
|
|
20
|
+
teacher:
|
|
21
|
+
name: stepwise
|
|
22
|
+
settings:
|
|
23
|
+
explain: true
|
|
24
|
+
|
|
25
|
+
``settings`` holds plain values as supplied. They are checked against the
|
|
26
|
+
component's settings class when the component is validated or created,
|
|
27
|
+
not here.
|
|
28
|
+
|
|
29
|
+
Attributes:
|
|
30
|
+
name: The registered name of the component.
|
|
31
|
+
settings: The supplied settings, or ``None`` for all defaults.
|
|
32
|
+
source: Where the entry came from, such as ``"run.yaml"``, for error
|
|
33
|
+
messages. Not part of equality.
|
|
34
|
+
path: The entry's path within the source, such as ``"teacher"``, for
|
|
35
|
+
error messages. Not part of equality.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
name: str
|
|
39
|
+
settings: Mapping[str, Any] | None = None
|
|
40
|
+
source: str | None = field(default=None, kw_only=True, compare=False)
|
|
41
|
+
path: str = field(default="", kw_only=True, compare=False)
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def from_mapping(
|
|
45
|
+
cls, entry: object, *, source: str | None = None, path: str = ""
|
|
46
|
+
) -> "ComponentSpec":
|
|
47
|
+
"""Read a component entry: a mapping with ``name`` and, optionally, ``settings``.
|
|
48
|
+
|
|
49
|
+
Raises:
|
|
50
|
+
ConfigError: The entry is not a mapping, lacks a name, has a
|
|
51
|
+
``settings`` value that is not a mapping, or has other keys.
|
|
52
|
+
Every problem is reported, with its path.
|
|
53
|
+
"""
|
|
54
|
+
problems: list[Problem] = []
|
|
55
|
+
if not isinstance(entry, Mapping):
|
|
56
|
+
problems.append(
|
|
57
|
+
Problem(path, f"expected a component entry {{name, settings}}, got {show(entry)}")
|
|
58
|
+
)
|
|
59
|
+
raise ConfigError(_subject("component entry", source), problems)
|
|
60
|
+
|
|
61
|
+
for key in entry:
|
|
62
|
+
if key not in _KEYS:
|
|
63
|
+
message = "unknown key in a component entry"
|
|
64
|
+
close = difflib.get_close_matches(str(key), _KEYS, n=1)
|
|
65
|
+
if close:
|
|
66
|
+
message += f"; did you mean {close[0]!r}?"
|
|
67
|
+
problems.append(
|
|
68
|
+
Problem(join_path(path, str(key)), f"{message} (allowed: name, settings)")
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
name = entry.get("name")
|
|
72
|
+
if "name" not in entry:
|
|
73
|
+
problems.append(Problem(join_path(path, "name"), "missing component name"))
|
|
74
|
+
elif not isinstance(name, str) or not name.strip():
|
|
75
|
+
problems.append(
|
|
76
|
+
Problem(join_path(path, "name"), f"expected a non-empty string, got {show(name)}")
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
settings = entry.get("settings")
|
|
80
|
+
if settings is not None and not isinstance(settings, Mapping):
|
|
81
|
+
problems.append(
|
|
82
|
+
Problem(join_path(path, "settings"), f"expected a mapping, got {show(settings)}")
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
if problems:
|
|
86
|
+
raise ConfigError(_subject("component entry", source), problems)
|
|
87
|
+
return cls(str(name), settings, source=source, path=path)
|
|
88
|
+
|
|
89
|
+
def to_mapping(self) -> dict[str, Any]:
|
|
90
|
+
"""The entry as plain values, ``{"name": ..., "settings": ...}``, ready to save."""
|
|
91
|
+
entry: dict[str, Any] = {"name": self.name}
|
|
92
|
+
if self.settings is not None:
|
|
93
|
+
entry["settings"] = dict(self.settings)
|
|
94
|
+
return entry
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _subject(what: str, source: str | None) -> str:
|
|
98
|
+
return f"{what} in {source}" if source else what
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""SSAPling data.
|
|
2
|
+
|
|
3
|
+
Responsibility: Sources, samplers, disjoint collections, records, datasets and
|
|
4
|
+
streams, storage, and batching.
|
|
5
|
+
|
|
6
|
+
Not its responsibility: What a problem means or how it is scored.
|
|
7
|
+
|
|
8
|
+
May import: core, tasks, and the result types of environments and teachers.
|
|
9
|
+
Enforced by tests/test_layering.py.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from .batching import batches, collators
|
|
13
|
+
from .collections import Collections, Drawn
|
|
14
|
+
from .encoding import Codec, JsonCodec, codecs
|
|
15
|
+
from .errors import (
|
|
16
|
+
HeldOutError,
|
|
17
|
+
SourceExhaustedError,
|
|
18
|
+
StoreError,
|
|
19
|
+
UnknownCollectionError,
|
|
20
|
+
UnknownDocumentError,
|
|
21
|
+
UnknownRecordError,
|
|
22
|
+
)
|
|
23
|
+
from .provenance import Provenance
|
|
24
|
+
from .records import (
|
|
25
|
+
RECORD_SCHEMA_VERSION,
|
|
26
|
+
AgentTiming,
|
|
27
|
+
Clock,
|
|
28
|
+
LateOutput,
|
|
29
|
+
Record,
|
|
30
|
+
RecordBuilder,
|
|
31
|
+
RecordHeader,
|
|
32
|
+
RecordStatus,
|
|
33
|
+
RecordStep,
|
|
34
|
+
RecordSummary,
|
|
35
|
+
TeacherPlacement,
|
|
36
|
+
)
|
|
37
|
+
from .sampling import (
|
|
38
|
+
GeneratedSampler,
|
|
39
|
+
GeneratedSettings,
|
|
40
|
+
Instances,
|
|
41
|
+
Sample,
|
|
42
|
+
Sampler,
|
|
43
|
+
StratifiedSampler,
|
|
44
|
+
StratifiedSettings,
|
|
45
|
+
UniformSampler,
|
|
46
|
+
samplers,
|
|
47
|
+
)
|
|
48
|
+
from .storage import STORE_FORMAT, STORE_VERSION, RecordStore, Store
|
|
49
|
+
|
|
50
|
+
__all__ = [
|
|
51
|
+
"RECORD_SCHEMA_VERSION",
|
|
52
|
+
"STORE_FORMAT",
|
|
53
|
+
"STORE_VERSION",
|
|
54
|
+
"AgentTiming",
|
|
55
|
+
"Clock",
|
|
56
|
+
"Codec",
|
|
57
|
+
"Collections",
|
|
58
|
+
"Drawn",
|
|
59
|
+
"GeneratedSampler",
|
|
60
|
+
"GeneratedSettings",
|
|
61
|
+
"HeldOutError",
|
|
62
|
+
"Instances",
|
|
63
|
+
"JsonCodec",
|
|
64
|
+
"LateOutput",
|
|
65
|
+
"Provenance",
|
|
66
|
+
"Record",
|
|
67
|
+
"RecordBuilder",
|
|
68
|
+
"RecordHeader",
|
|
69
|
+
"RecordStatus",
|
|
70
|
+
"RecordStep",
|
|
71
|
+
"RecordStore",
|
|
72
|
+
"RecordSummary",
|
|
73
|
+
"Sample",
|
|
74
|
+
"Sampler",
|
|
75
|
+
"SourceExhaustedError",
|
|
76
|
+
"Store",
|
|
77
|
+
"StoreError",
|
|
78
|
+
"StratifiedSampler",
|
|
79
|
+
"StratifiedSettings",
|
|
80
|
+
"TeacherPlacement",
|
|
81
|
+
"UniformSampler",
|
|
82
|
+
"UnknownCollectionError",
|
|
83
|
+
"UnknownDocumentError",
|
|
84
|
+
"UnknownRecordError",
|
|
85
|
+
"batches",
|
|
86
|
+
"codecs",
|
|
87
|
+
"collators",
|
|
88
|
+
"samplers",
|
|
89
|
+
]
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Matching descriptors against ``where``: the rule collections and aggregations share."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
__all__ = ["matches"]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def matches(descriptors: Mapping[str, Any], where: Mapping[str, Any]) -> bool:
|
|
10
|
+
"""Whether ``descriptors`` hold every value that ``where`` names.
|
|
11
|
+
|
|
12
|
+
A list and a tuple with equal items are equal, at any depth: a YAML or
|
|
13
|
+
JSON file gives a tuple descriptor, such as a length pair ``(2, 1)``, as
|
|
14
|
+
the list ``[2, 1]``.
|
|
15
|
+
"""
|
|
16
|
+
return all(key in descriptors and _same(descriptors[key], v) for key, v in where.items())
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _same(a: Any, b: Any) -> bool:
|
|
20
|
+
if isinstance(a, list | tuple) and isinstance(b, list | tuple):
|
|
21
|
+
return len(a) == len(b) and all(_same(x, y) for x, y in zip(a, b, strict=True))
|
|
22
|
+
return bool(a == b)
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Batching: grouping items for a consumer, with collation optionally in worker processes.
|
|
2
|
+
|
|
3
|
+
**Collation** turns a list of items (records, drawn instances, anything)
|
|
4
|
+
into one batch, for example by padding and stacking. It depends on the
|
|
5
|
+
model's representation, so the project supplies it: as a function, or as a
|
|
6
|
+
registered **collator** component built from a ``ComponentSpec``. Data does
|
|
7
|
+
not require torch or any other library.
|
|
8
|
+
|
|
9
|
+
Collation can run in worker processes. They are started with ``spawn``,
|
|
10
|
+
which works on every platform, so each worker builds its collator afresh:
|
|
11
|
+
a function or picklable object is sent to it, and a ``ComponentSpec`` is
|
|
12
|
+
rebuilt from the ``collators`` registry, after ``setup`` (such as the
|
|
13
|
+
project's ``register_components``) has run in that worker.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from collections import deque
|
|
17
|
+
from collections.abc import Callable, Iterable, Iterator
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from ..core import ComponentSpec, Registry
|
|
21
|
+
from ..core._declarations import check_int
|
|
22
|
+
|
|
23
|
+
__all__ = ["batches", "collators"]
|
|
24
|
+
|
|
25
|
+
collators: Registry[Callable[..., Callable[[list[Any]], Any]]] = Registry("collator")
|
|
26
|
+
"""Registered collators. Also available as ``ssapling.registries.collators``.
|
|
27
|
+
|
|
28
|
+
A collator is built with its settings and then called with a list of items,
|
|
29
|
+
returning a batch. SSAPling registers none.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def batches(
|
|
34
|
+
items: Iterable[Any],
|
|
35
|
+
collate: Callable[[list[Any]], Any] | ComponentSpec,
|
|
36
|
+
*,
|
|
37
|
+
batch_size: int,
|
|
38
|
+
drop_last: bool = False,
|
|
39
|
+
workers: int = 0,
|
|
40
|
+
setup: Callable[[], None] | None = None,
|
|
41
|
+
) -> Iterator[Any]:
|
|
42
|
+
"""Group ``items`` into lists of ``batch_size`` and collate each into a batch.
|
|
43
|
+
|
|
44
|
+
``items`` may be a dataset or a stream, even an unbounded one: it is
|
|
45
|
+
read only as far as the batches are taken. The batches come out in the
|
|
46
|
+
order of the items.
|
|
47
|
+
|
|
48
|
+
Example::
|
|
49
|
+
|
|
50
|
+
for batch in batches(records, pad_and_stack, batch_size=32):
|
|
51
|
+
model.learn("learn_from_batch", batch=batch)
|
|
52
|
+
|
|
53
|
+
batches(records, ComponentSpec("pad", {"width": 30}), batch_size=32,
|
|
54
|
+
workers=4, setup=register_components)
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
items: What to batch.
|
|
58
|
+
collate: Turns a list of items into a batch: a function or other
|
|
59
|
+
callable, or a ``ComponentSpec`` naming a registered collator.
|
|
60
|
+
batch_size: How many items per batch.
|
|
61
|
+
drop_last: Drop a last batch that has fewer than ``batch_size``
|
|
62
|
+
items, instead of collating it.
|
|
63
|
+
workers: How many worker processes collate batches. 0 collates in
|
|
64
|
+
this process. With workers, ``collate`` and the items must be
|
|
65
|
+
picklable, and a function must be defined at module level.
|
|
66
|
+
setup: For workers only: a module-level function each worker runs
|
|
67
|
+
once before collating, such as the project's
|
|
68
|
+
``register_components``, so a ``ComponentSpec`` can be built
|
|
69
|
+
from the registries there.
|
|
70
|
+
|
|
71
|
+
Raises:
|
|
72
|
+
TypeError: ``collate`` is neither callable nor a ``ComponentSpec``,
|
|
73
|
+
or ``setup`` is not callable.
|
|
74
|
+
ValueError: ``batch_size`` is less than 1, or ``workers`` is
|
|
75
|
+
negative.
|
|
76
|
+
UnknownComponentError, ConfigError: A ``ComponentSpec`` names no
|
|
77
|
+
registered collator, or invalid settings. Raised here when
|
|
78
|
+
``workers`` is 0; with workers, from the first batch, as is an
|
|
79
|
+
error raised by ``setup``.
|
|
80
|
+
|
|
81
|
+
An error raised by ``collate`` reaches the caller as itself, where that
|
|
82
|
+
batch would have been, whether it runs here or in a worker.
|
|
83
|
+
"""
|
|
84
|
+
check_int(batch_size, "batch_size", minimum=1)
|
|
85
|
+
check_int(workers, "workers", minimum=0)
|
|
86
|
+
if not (callable(collate) or isinstance(collate, ComponentSpec)):
|
|
87
|
+
raise TypeError(f"collate must be callable or a ComponentSpec, got {collate!r}")
|
|
88
|
+
if setup is not None and not callable(setup):
|
|
89
|
+
raise TypeError(f"setup must be a function, got {setup!r}")
|
|
90
|
+
chunks = _chunks(items, batch_size, drop_last)
|
|
91
|
+
if workers == 0:
|
|
92
|
+
return map(_collator(collate), chunks)
|
|
93
|
+
return _in_workers(chunks, collate, workers, setup)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _chunks(items: Iterable[Any], size: int, drop_last: bool) -> Iterator[list[Any]]:
|
|
97
|
+
chunk: list[Any] = []
|
|
98
|
+
for item in items:
|
|
99
|
+
chunk.append(item)
|
|
100
|
+
if len(chunk) == size:
|
|
101
|
+
yield chunk
|
|
102
|
+
chunk = []
|
|
103
|
+
if chunk and not drop_last:
|
|
104
|
+
yield chunk
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _collator(collate: Callable[[list[Any]], Any] | ComponentSpec) -> Callable[[list[Any]], Any]:
|
|
108
|
+
if isinstance(collate, ComponentSpec):
|
|
109
|
+
collator: Callable[[list[Any]], Any] = collators.create_from(collate)
|
|
110
|
+
return collator
|
|
111
|
+
return collate
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _in_workers(
|
|
115
|
+
chunks: Iterator[list[Any]],
|
|
116
|
+
collate: Callable[[list[Any]], Any] | ComponentSpec,
|
|
117
|
+
workers: int,
|
|
118
|
+
setup: Callable[[], None] | None,
|
|
119
|
+
) -> Iterator[Any]:
|
|
120
|
+
# Imported here: importing ssapling must not load multiprocessing.
|
|
121
|
+
import multiprocessing
|
|
122
|
+
from concurrent.futures import Future, ProcessPoolExecutor
|
|
123
|
+
|
|
124
|
+
pool = ProcessPoolExecutor(
|
|
125
|
+
max_workers=workers,
|
|
126
|
+
mp_context=multiprocessing.get_context("spawn"),
|
|
127
|
+
initializer=_start_worker,
|
|
128
|
+
initargs=(setup, collate),
|
|
129
|
+
)
|
|
130
|
+
pending: deque[Future[Any]] = deque()
|
|
131
|
+
try:
|
|
132
|
+
for chunk in chunks:
|
|
133
|
+
pending.append(pool.submit(_collate_in_worker, chunk))
|
|
134
|
+
if len(pending) >= 2 * workers: # a few batches ahead, never the whole stream
|
|
135
|
+
yield pending.popleft().result()
|
|
136
|
+
while pending:
|
|
137
|
+
yield pending.popleft().result()
|
|
138
|
+
finally:
|
|
139
|
+
pool.shutdown(cancel_futures=True)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# In each worker process
|
|
143
|
+
|
|
144
|
+
_worker_collate: Callable[[list[Any]], Any] | None = None
|
|
145
|
+
_worker_error: Exception | None = None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _start_worker(
|
|
149
|
+
setup: Callable[[], None] | None, collate: Callable[[list[Any]], Any] | ComponentSpec
|
|
150
|
+
) -> None:
|
|
151
|
+
global _worker_collate, _worker_error
|
|
152
|
+
try:
|
|
153
|
+
if setup is not None:
|
|
154
|
+
setup()
|
|
155
|
+
_worker_collate = _collator(collate)
|
|
156
|
+
except Exception as error:
|
|
157
|
+
# Raised from the first batch instead, so the caller sees this error
|
|
158
|
+
# rather than a pool that broke for no stated reason.
|
|
159
|
+
_worker_error = error
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _collate_in_worker(chunk: list[Any]) -> Any:
|
|
163
|
+
if _worker_error is not None:
|
|
164
|
+
raise _worker_error
|
|
165
|
+
assert _worker_collate is not None, "the worker was not started"
|
|
166
|
+
return _worker_collate(chunk)
|