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
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
"""Collections: named sets of instances drawn from one source, which never overlap.
|
|
2
|
+
|
|
3
|
+
Each collection reserves the problems it holds, by their ``problem_key``
|
|
4
|
+
(the equivalence key, or the id when there is none), and every later draw
|
|
5
|
+
rejects reserved problems. So a validation set and a test set never share a
|
|
6
|
+
problem, and the **remainder**, a stream of everything else drawn on the
|
|
7
|
+
fly, never yields one either. Every item served carries its provenance.
|
|
8
|
+
|
|
9
|
+
A **dataset** is finite and re-readable: a built collection is a tuple. A
|
|
10
|
+
**stream** may be unbounded: the remainder is an iterator. Both are
|
|
11
|
+
iterated the same way; check ``isinstance(items, collections.abc.Sized)``
|
|
12
|
+
or ``Sequence`` before counting or indexing.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import dataclasses
|
|
16
|
+
import random
|
|
17
|
+
from collections.abc import Hashable, Iterable, Iterator, Mapping
|
|
18
|
+
from collections.abc import Set as AbstractSet
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from ..core import settings_to_dict
|
|
23
|
+
from ..core._declarations import check_identifier, check_int, keyed, name_of
|
|
24
|
+
from ..tasks import Instance
|
|
25
|
+
from ..tasks import supports as task_supports
|
|
26
|
+
from ._matching import matches
|
|
27
|
+
from .errors import HeldOutError, SourceExhaustedError, UnknownCollectionError
|
|
28
|
+
from .provenance import Provenance
|
|
29
|
+
from .sampling import Sample, Sampler
|
|
30
|
+
|
|
31
|
+
__all__ = ["Collections", "Drawn"]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True, slots=True)
|
|
35
|
+
class Drawn:
|
|
36
|
+
"""An instance as Data serves it: with where it came from.
|
|
37
|
+
|
|
38
|
+
Attributes:
|
|
39
|
+
instance: The instance.
|
|
40
|
+
provenance: Its source, collection, sampler, parameters and seed.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
instance: Instance
|
|
44
|
+
provenance: Provenance
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True, slots=True)
|
|
48
|
+
class _Collection:
|
|
49
|
+
items: tuple[Drawn, ...]
|
|
50
|
+
held_out: bool
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Collections:
|
|
54
|
+
"""The collections drawn from one source.
|
|
55
|
+
|
|
56
|
+
Example::
|
|
57
|
+
|
|
58
|
+
collections = Collections(task, source_name="addition")
|
|
59
|
+
collections.build("validation", sampler=uniform, size=1000, seed=1)
|
|
60
|
+
collections.build("test", sampler=uniform, size=1000, seed=2, held_out=True)
|
|
61
|
+
training = collections.remainder(sampler=curriculum, seed=3) # drawn on the fly
|
|
62
|
+
|
|
63
|
+
collections.get("validation") # a tuple of Drawn
|
|
64
|
+
collections.get("test", purpose="evaluation") # held out: needs this purpose
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
source: Where the instances come from: anything with the task
|
|
68
|
+
feature ``"generate"`` or ``"enumerate"``.
|
|
69
|
+
source_name: The source's name in provenance, such as its
|
|
70
|
+
registered name. Defaults to its class name. Give the registered
|
|
71
|
+
name to make every item rebuildable through the registry.
|
|
72
|
+
source_settings: The source's settings in provenance. Defaults to
|
|
73
|
+
its ``config`` (the validated settings a registry gives a
|
|
74
|
+
component), if it has one.
|
|
75
|
+
|
|
76
|
+
Sources that arrive already divided, such as separately published
|
|
77
|
+
training and evaluation sets, are separate sources, each with its own
|
|
78
|
+
``Collections``.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
def __init__(
|
|
82
|
+
self,
|
|
83
|
+
source: object,
|
|
84
|
+
*,
|
|
85
|
+
source_name: str | None = None,
|
|
86
|
+
source_settings: Mapping[str, Any] | None = None,
|
|
87
|
+
) -> None:
|
|
88
|
+
if not (task_supports(source, "generate") or task_supports(source, "enumerate")):
|
|
89
|
+
raise TypeError(
|
|
90
|
+
f"{name_of(source)} is not a source: it has neither generate(params, seed) "
|
|
91
|
+
"nor ids() and get(id)"
|
|
92
|
+
)
|
|
93
|
+
self._source = source
|
|
94
|
+
self._source_name = source_name or name_of(source)
|
|
95
|
+
self._source_settings = (
|
|
96
|
+
keyed(source_settings, "source_settings", "names")
|
|
97
|
+
if source_settings is not None
|
|
98
|
+
else _settings_of(source)
|
|
99
|
+
)
|
|
100
|
+
self._collections: dict[str, _Collection] = {}
|
|
101
|
+
self._reserved: set[Hashable] = set()
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def source(self) -> object:
|
|
105
|
+
"""The source every collection is drawn from."""
|
|
106
|
+
return self._source
|
|
107
|
+
|
|
108
|
+
def names(self) -> tuple[str, ...]:
|
|
109
|
+
"""The names of the built collections, in the order they were built."""
|
|
110
|
+
return tuple(self._collections)
|
|
111
|
+
|
|
112
|
+
def held_out(self, name: str) -> bool:
|
|
113
|
+
"""Whether the collection ``name`` is held out."""
|
|
114
|
+
return self._collection(name).held_out
|
|
115
|
+
|
|
116
|
+
def build(
|
|
117
|
+
self,
|
|
118
|
+
name: str,
|
|
119
|
+
*,
|
|
120
|
+
sampler: Sampler,
|
|
121
|
+
size: int,
|
|
122
|
+
seed: int,
|
|
123
|
+
held_out: bool = False,
|
|
124
|
+
where: Mapping[str, Any] | None = None,
|
|
125
|
+
max_draws: int = 1000,
|
|
126
|
+
) -> tuple[Drawn, ...]:
|
|
127
|
+
"""Draw a collection of ``size`` distinct problems and reserve them.
|
|
128
|
+
|
|
129
|
+
Each draw gets its own seed, derived from ``seed``, so the same
|
|
130
|
+
sampler, seed and earlier collections give the same collection.
|
|
131
|
+
A draw is rejected when its problem is reserved, by an earlier
|
|
132
|
+
collection or by this one, or when its descriptors do not match
|
|
133
|
+
``where``. If ``max_draws`` draws in a row are rejected, building
|
|
134
|
+
stops with an error and reserves nothing.
|
|
135
|
+
|
|
136
|
+
Args:
|
|
137
|
+
name: The collection's name, new in these collections.
|
|
138
|
+
sampler: Picks the instances; it must draw from this source.
|
|
139
|
+
size: How many instances.
|
|
140
|
+
seed: Seeds every draw.
|
|
141
|
+
held_out: Serve the collection only with
|
|
142
|
+
``purpose="evaluation"`` (see ``get``).
|
|
143
|
+
where: Optional. Descriptor values every instance must have,
|
|
144
|
+
such as ``{"digits": 3}``.
|
|
145
|
+
max_draws: How many draws in a row may be rejected before giving
|
|
146
|
+
up.
|
|
147
|
+
|
|
148
|
+
Returns:
|
|
149
|
+
The collection: a tuple of ``Drawn``, each with its provenance.
|
|
150
|
+
|
|
151
|
+
Raises:
|
|
152
|
+
SourceExhaustedError: ``max_draws`` draws in a row were rejected.
|
|
153
|
+
ValueError: ``name`` is taken or empty, ``size`` is negative,
|
|
154
|
+
``max_draws`` is less than 1, or the sampler draws from
|
|
155
|
+
another source.
|
|
156
|
+
TypeError: An argument of the wrong type, or the sampler did not
|
|
157
|
+
return a ``Sample``.
|
|
158
|
+
"""
|
|
159
|
+
self._check_new_name(name)
|
|
160
|
+
check_int(size, "size", minimum=0)
|
|
161
|
+
if where is not None:
|
|
162
|
+
where = keyed(where, "where", "descriptor names")
|
|
163
|
+
self._check_sampler(sampler, seed, max_draws)
|
|
164
|
+
|
|
165
|
+
rng = random.Random(seed)
|
|
166
|
+
taken: set[Hashable] = set()
|
|
167
|
+
items: list[Drawn] = []
|
|
168
|
+
while len(items) < size:
|
|
169
|
+
sample, draw_seed = self._draw(
|
|
170
|
+
sampler, rng, max_draws, taken=taken, where=where, building=name
|
|
171
|
+
)
|
|
172
|
+
taken.add(sample.instance.problem_key)
|
|
173
|
+
items.append(self._drawn(sample, draw_seed, sampler, collection=name))
|
|
174
|
+
|
|
175
|
+
self._reserved |= taken
|
|
176
|
+
self._collections[name] = _Collection(tuple(items), held_out=bool(held_out))
|
|
177
|
+
return self._collections[name].items
|
|
178
|
+
|
|
179
|
+
def add(
|
|
180
|
+
self, name: str, items: Iterable[Drawn], *, held_out: bool = False
|
|
181
|
+
) -> tuple[Drawn, ...]:
|
|
182
|
+
"""Add a collection drawn elsewhere, such as one loaded from storage, and reserve it.
|
|
183
|
+
|
|
184
|
+
The same rules hold as for a built collection: at most one instance
|
|
185
|
+
per problem, and no problem another collection has reserved.
|
|
186
|
+
|
|
187
|
+
Raises:
|
|
188
|
+
ValueError: ``name`` is taken or empty, two items are the same
|
|
189
|
+
problem, or an item's problem is already reserved.
|
|
190
|
+
TypeError: An item is not a ``Drawn``.
|
|
191
|
+
"""
|
|
192
|
+
self._check_new_name(name)
|
|
193
|
+
added = tuple(items)
|
|
194
|
+
taken: set[Hashable] = set()
|
|
195
|
+
for drawn in added:
|
|
196
|
+
if not isinstance(drawn, Drawn):
|
|
197
|
+
raise TypeError(f"a collection holds Drawn items, got {drawn!r}")
|
|
198
|
+
key = drawn.instance.problem_key
|
|
199
|
+
if key in taken or key in self._reserved:
|
|
200
|
+
raise ValueError(
|
|
201
|
+
f"collection {name!r}: instance {drawn.instance.id!r} is problem {key!r}, "
|
|
202
|
+
"which is already in this collection or reserved by another"
|
|
203
|
+
)
|
|
204
|
+
taken.add(key)
|
|
205
|
+
self._reserved |= taken
|
|
206
|
+
self._collections[name] = _Collection(added, held_out=bool(held_out))
|
|
207
|
+
return added
|
|
208
|
+
|
|
209
|
+
def get(self, name: str, *, purpose: str | None = None) -> tuple[Drawn, ...]:
|
|
210
|
+
"""The collection ``name``.
|
|
211
|
+
|
|
212
|
+
A held-out collection is served only to a consumer that declares
|
|
213
|
+
``purpose="evaluation"``. How strictly that is used is the
|
|
214
|
+
downstream project's choice.
|
|
215
|
+
|
|
216
|
+
Raises:
|
|
217
|
+
UnknownCollectionError: No collection is named ``name``.
|
|
218
|
+
HeldOutError: The collection is held out and ``purpose`` is not
|
|
219
|
+
``"evaluation"``.
|
|
220
|
+
"""
|
|
221
|
+
collection = self._collection(name)
|
|
222
|
+
if collection.held_out and purpose != "evaluation":
|
|
223
|
+
raise HeldOutError(name, purpose)
|
|
224
|
+
return collection.items
|
|
225
|
+
|
|
226
|
+
def remainder(self, *, sampler: Sampler, seed: int, max_draws: int = 1000) -> Iterator[Drawn]:
|
|
227
|
+
"""A stream of instances outside every collection, drawn on the fly.
|
|
228
|
+
|
|
229
|
+
It never ends by itself. Each draw is checked against the
|
|
230
|
+
collections as they are at that moment, so a collection built later
|
|
231
|
+
is excluded from then on. The same problem may be drawn more than
|
|
232
|
+
once: the remainder reserves nothing. Its items' provenance has no
|
|
233
|
+
collection.
|
|
234
|
+
|
|
235
|
+
Raises:
|
|
236
|
+
SourceExhaustedError: When iterated: ``max_draws`` draws in a row
|
|
237
|
+
gave reserved problems.
|
|
238
|
+
ValueError, TypeError: As for ``build``, when called.
|
|
239
|
+
"""
|
|
240
|
+
self._check_sampler(sampler, seed, max_draws)
|
|
241
|
+
return self._remainder(sampler, seed, max_draws)
|
|
242
|
+
|
|
243
|
+
def _remainder(self, sampler: Sampler, seed: int, max_draws: int) -> Iterator[Drawn]:
|
|
244
|
+
rng = random.Random(seed)
|
|
245
|
+
while True:
|
|
246
|
+
sample, draw_seed = self._draw(
|
|
247
|
+
sampler, rng, max_draws, taken=frozenset(), where=None, building=None
|
|
248
|
+
)
|
|
249
|
+
yield self._drawn(sample, draw_seed, sampler, collection=None)
|
|
250
|
+
|
|
251
|
+
def _draw(
|
|
252
|
+
self,
|
|
253
|
+
sampler: Sampler,
|
|
254
|
+
rng: random.Random,
|
|
255
|
+
max_draws: int,
|
|
256
|
+
*,
|
|
257
|
+
taken: AbstractSet[Hashable],
|
|
258
|
+
where: Mapping[str, Any] | None,
|
|
259
|
+
building: str | None,
|
|
260
|
+
) -> tuple[Sample, int]:
|
|
261
|
+
"""The first acceptable sample within ``max_draws`` draws, and its seed.
|
|
262
|
+
|
|
263
|
+
A sample is rejected when its problem is reserved, or already
|
|
264
|
+
``taken`` by the collection being built.
|
|
265
|
+
"""
|
|
266
|
+
for _ in range(max_draws):
|
|
267
|
+
draw_seed = rng.getrandbits(63)
|
|
268
|
+
sample = sampler.draw(seed=draw_seed)
|
|
269
|
+
if not isinstance(sample, Sample):
|
|
270
|
+
raise TypeError(
|
|
271
|
+
f"{name_of(sampler)}.draw must return a Sample, got {type(sample).__name__}"
|
|
272
|
+
)
|
|
273
|
+
key = sample.instance.problem_key
|
|
274
|
+
if key in self._reserved or key in taken:
|
|
275
|
+
continue
|
|
276
|
+
if where is not None and not _matches(sample.instance, where):
|
|
277
|
+
continue
|
|
278
|
+
return sample, draw_seed
|
|
279
|
+
raise SourceExhaustedError(name_of(sampler), self.names(), max_draws, building=building)
|
|
280
|
+
|
|
281
|
+
def _drawn(
|
|
282
|
+
self, sample: Sample, seed: int, sampler: Sampler, *, collection: str | None
|
|
283
|
+
) -> Drawn:
|
|
284
|
+
provenance = Provenance(
|
|
285
|
+
source=self._source_name,
|
|
286
|
+
source_settings=self._source_settings,
|
|
287
|
+
collection=collection,
|
|
288
|
+
sampler=name_of(sampler),
|
|
289
|
+
sampler_settings=_settings_of(sampler),
|
|
290
|
+
params=sample.params,
|
|
291
|
+
seed=seed,
|
|
292
|
+
position=sample.position,
|
|
293
|
+
)
|
|
294
|
+
return Drawn(sample.instance, provenance)
|
|
295
|
+
|
|
296
|
+
def _check_sampler(self, sampler: object, seed: object, max_draws: object) -> None:
|
|
297
|
+
if not callable(getattr(sampler, "draw", None)):
|
|
298
|
+
raise TypeError(f"{name_of(sampler)} has no draw method, so it is not a sampler")
|
|
299
|
+
drawn_from = getattr(sampler, "source", self._source)
|
|
300
|
+
if drawn_from is not self._source:
|
|
301
|
+
raise ValueError(
|
|
302
|
+
f"{name_of(sampler)} draws from {name_of(drawn_from)}, not from this source "
|
|
303
|
+
f"({name_of(self._source)}), so its draws could not respect the reservations"
|
|
304
|
+
)
|
|
305
|
+
check_int(seed, "seed")
|
|
306
|
+
check_int(max_draws, "max_draws", minimum=1)
|
|
307
|
+
|
|
308
|
+
def _check_new_name(self, name: object) -> None:
|
|
309
|
+
check_identifier(name, "a collection name")
|
|
310
|
+
if name in self._collections:
|
|
311
|
+
raise ValueError(f"collection {name!r} is already built")
|
|
312
|
+
|
|
313
|
+
def _collection(self, name: str) -> _Collection:
|
|
314
|
+
try:
|
|
315
|
+
return self._collections[name]
|
|
316
|
+
except KeyError:
|
|
317
|
+
raise UnknownCollectionError(name, self._collections) from None
|
|
318
|
+
|
|
319
|
+
def __contains__(self, name: object) -> bool:
|
|
320
|
+
return name in self._collections
|
|
321
|
+
|
|
322
|
+
def __repr__(self) -> str:
|
|
323
|
+
return f"Collections({self._source_name!r}, collections={list(self._collections)})"
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _settings_of(component: object) -> dict[str, Any]:
|
|
327
|
+
"""A component's settings as plain values: its ``config``, if that is a settings dataclass."""
|
|
328
|
+
config = getattr(component, "config", None)
|
|
329
|
+
if dataclasses.is_dataclass(config) and not isinstance(config, type):
|
|
330
|
+
return settings_to_dict(config)
|
|
331
|
+
return {}
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _matches(instance: Instance, where: Mapping[str, Any]) -> bool:
|
|
335
|
+
return matches(instance.descriptors, where)
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Codecs: how payloads are written to storage and read back.
|
|
2
|
+
|
|
3
|
+
The store owns a file's structure; a codec owns the payloads inside it
|
|
4
|
+
(observations, actions, predictions, teacher contributions, an instance's
|
|
5
|
+
inputs). It turns them into **JSON-ready values** (``None``, booleans,
|
|
6
|
+
numbers, strings, lists, and dicts with string keys) and back, so every
|
|
7
|
+
stored file is readable JSON lines whatever the payloads are.
|
|
8
|
+
|
|
9
|
+
The built-in ``"json"`` codec handles plain Python values, and tags tuples
|
|
10
|
+
and bytes so they come back as tuples and bytes. A project whose payloads
|
|
11
|
+
hold other types, such as arrays, registers its own codec, usually by
|
|
12
|
+
handling those types and passing everything else to ``JsonCodec``::
|
|
13
|
+
|
|
14
|
+
class ArrayCodec:
|
|
15
|
+
def encode(self, value):
|
|
16
|
+
if isinstance(value, np.ndarray):
|
|
17
|
+
return {"__ndarray__": value.tolist(), "dtype": str(value.dtype)}
|
|
18
|
+
...
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
import base64
|
|
22
|
+
from collections.abc import Callable, Mapping
|
|
23
|
+
from typing import Any, Protocol
|
|
24
|
+
|
|
25
|
+
from ..core import Registry
|
|
26
|
+
|
|
27
|
+
__all__ = ["Codec", "JsonCodec", "codecs"]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Codec(Protocol):
|
|
31
|
+
"""What every codec provides: payloads to JSON-ready values, and back."""
|
|
32
|
+
|
|
33
|
+
def encode(self, value: Any) -> Any:
|
|
34
|
+
"""``value`` as JSON-ready values. Raise ``TypeError`` for a value it cannot encode."""
|
|
35
|
+
...
|
|
36
|
+
|
|
37
|
+
def decode(self, value: Any) -> Any:
|
|
38
|
+
"""The value ``encode`` was given, from what it returned."""
|
|
39
|
+
...
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
_TUPLE, _BYTES, _DICT = "__tuple__", "__bytes__", "__dict__"
|
|
43
|
+
_TAGS = (_TUPLE, _BYTES, _DICT)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class JsonCodec:
|
|
47
|
+
"""Plain Python values, with tuples and bytes tagged so they survive the round trip.
|
|
48
|
+
|
|
49
|
+
It encodes ``None``, booleans, numbers, strings, lists, tuples, bytes,
|
|
50
|
+
and mappings with string keys. A tuple becomes ``{"__tuple__": [...]}``
|
|
51
|
+
and bytes become ``{"__bytes__": "<base64>"}``; a mapping that happens to
|
|
52
|
+
look like a tag is wrapped as ``{"__dict__": {...}}``, so nothing is
|
|
53
|
+
misread. Any other value raises ``TypeError`` naming where it is.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def encode(self, value: Any) -> Any:
|
|
57
|
+
"""``value`` as JSON-ready values."""
|
|
58
|
+
return _encode(value, "")
|
|
59
|
+
|
|
60
|
+
def decode(self, value: Any) -> Any:
|
|
61
|
+
"""The value ``encode`` was given."""
|
|
62
|
+
return _decode(value)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
codecs: Registry[Callable[..., Codec]] = Registry("codec")
|
|
66
|
+
"""Registered codecs. Also available as ``ssapling.registries.codecs``."""
|
|
67
|
+
codecs.register("json", JsonCodec)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _encode(value: Any, path: str) -> Any:
|
|
71
|
+
if value is None or isinstance(value, bool | int | float | str):
|
|
72
|
+
return value
|
|
73
|
+
if isinstance(value, list):
|
|
74
|
+
return [_encode(item, f"{path}[{i}]") for i, item in enumerate(value)]
|
|
75
|
+
if isinstance(value, tuple):
|
|
76
|
+
return {_TUPLE: [_encode(item, f"{path}[{i}]") for i, item in enumerate(value)]}
|
|
77
|
+
if isinstance(value, bytes | bytearray):
|
|
78
|
+
return {_BYTES: base64.b64encode(value).decode("ascii")}
|
|
79
|
+
if isinstance(value, Mapping):
|
|
80
|
+
encoded = {}
|
|
81
|
+
for key, item in value.items():
|
|
82
|
+
if not isinstance(key, str):
|
|
83
|
+
raise TypeError(f"{path or 'the value'}: keys must be strings, got {key!r}")
|
|
84
|
+
encoded[key] = _encode(item, f"{path}.{key}" if path else key)
|
|
85
|
+
if len(encoded) == 1 and next(iter(encoded)) in _TAGS:
|
|
86
|
+
return {_DICT: encoded}
|
|
87
|
+
return encoded
|
|
88
|
+
raise TypeError(
|
|
89
|
+
f"{path or 'the value'}: the json codec cannot encode {type(value).__name__}; "
|
|
90
|
+
"register a codec that handles it"
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _decode(value: Any) -> Any:
|
|
95
|
+
if isinstance(value, list):
|
|
96
|
+
return [_decode(item) for item in value]
|
|
97
|
+
if isinstance(value, dict):
|
|
98
|
+
if len(value) == 1:
|
|
99
|
+
((key, inner),) = value.items()
|
|
100
|
+
if key == _TUPLE:
|
|
101
|
+
return tuple(_decode(item) for item in inner)
|
|
102
|
+
if key == _BYTES:
|
|
103
|
+
return base64.b64decode(inner)
|
|
104
|
+
if key == _DICT:
|
|
105
|
+
return {k: _decode(v) for k, v in inner.items()}
|
|
106
|
+
return {k: _decode(v) for k, v in value.items()}
|
|
107
|
+
return value
|
ssapling/data/errors.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Errors specific to data."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
4
|
+
|
|
5
|
+
from ..core.errors import SSAPlingError
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SourceExhaustedError(SSAPlingError, LookupError):
|
|
9
|
+
"""A sampler found no usable instance within the allowed number of draws.
|
|
10
|
+
|
|
11
|
+
Raised instead of retrying forever, when every draw gave an instance of
|
|
12
|
+
a problem already reserved by a collection (or, while building, one that
|
|
13
|
+
did not match ``where``). The source may be used up, or the reserved
|
|
14
|
+
collections may cover most of it.
|
|
15
|
+
|
|
16
|
+
Attributes:
|
|
17
|
+
sampler: The sampler's class name.
|
|
18
|
+
reserved: The names of the collections whose problems were reserved.
|
|
19
|
+
draws: How many draws were made for the one instance.
|
|
20
|
+
building: The collection being built, or ``None`` for the remainder.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self, sampler: str, reserved: Iterable[str], draws: int, *, building: str | None
|
|
25
|
+
) -> None:
|
|
26
|
+
self.sampler = sampler
|
|
27
|
+
self.reserved = tuple(reserved)
|
|
28
|
+
self.draws = draws
|
|
29
|
+
self.building = building
|
|
30
|
+
target = f"for collection {building!r}" if building else "for the remainder"
|
|
31
|
+
collections = ", ".join(repr(name) for name in self.reserved) or "none"
|
|
32
|
+
super().__init__(
|
|
33
|
+
f"{sampler} drew {draws} times {target} without finding an instance outside the "
|
|
34
|
+
f"reserved collections ({collections}); the source may be used up. Raise "
|
|
35
|
+
"max_draws, use a larger source, or reserve less."
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class UnknownCollectionError(SSAPlingError, LookupError):
|
|
40
|
+
"""A collection was asked for by a name that has not been built.
|
|
41
|
+
|
|
42
|
+
Attributes:
|
|
43
|
+
name: The name asked for.
|
|
44
|
+
available: The names of the collections that exist, in the order built.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
def __init__(self, name: str, available: Iterable[str]) -> None:
|
|
48
|
+
self.name = name
|
|
49
|
+
self.available = tuple(available)
|
|
50
|
+
built = ", ".join(repr(n) for n in self.available) or "none"
|
|
51
|
+
super().__init__(f"No collection {name!r}; the collections are: {built}.")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class HeldOutError(SSAPlingError, LookupError):
|
|
55
|
+
"""A held-out collection was asked for without an evaluation purpose.
|
|
56
|
+
|
|
57
|
+
Attributes:
|
|
58
|
+
name: The collection's name.
|
|
59
|
+
purpose: The purpose that was declared, or ``None``.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
def __init__(self, name: str, purpose: str | None) -> None:
|
|
63
|
+
self.name = name
|
|
64
|
+
self.purpose = purpose
|
|
65
|
+
declared = f"purpose {purpose!r}" if purpose else "no purpose"
|
|
66
|
+
super().__init__(
|
|
67
|
+
f"Collection {name!r} is held out, so it is served only with "
|
|
68
|
+
f"purpose='evaluation', not with {declared}."
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class UnknownRecordError(SSAPlingError, LookupError):
|
|
73
|
+
"""A record was asked for that the store does not hold.
|
|
74
|
+
|
|
75
|
+
Attributes:
|
|
76
|
+
record_id: The id asked for.
|
|
77
|
+
store: Where the store is.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
def __init__(self, record_id: str, store: str) -> None:
|
|
81
|
+
self.record_id = record_id
|
|
82
|
+
self.store = store
|
|
83
|
+
super().__init__(f"The store at {store} holds no record {record_id!r}.")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class UnknownDocumentError(SSAPlingError, LookupError):
|
|
87
|
+
"""A document was asked for that the store does not hold.
|
|
88
|
+
|
|
89
|
+
Attributes:
|
|
90
|
+
name: The name asked for.
|
|
91
|
+
store: Where the store is.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
def __init__(self, name: str, store: str) -> None:
|
|
95
|
+
self.name = name
|
|
96
|
+
self.store = store
|
|
97
|
+
super().__init__(f"The store at {store} holds no document {name!r}.")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class StoreError(SSAPlingError, ValueError):
|
|
101
|
+
"""A store's files are not what SSAPling writes: not a store, a newer format, or damaged.
|
|
102
|
+
|
|
103
|
+
The message names the file, and the line where there is one.
|
|
104
|
+
"""
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Provenance: where an instance or record came from, in plain values.
|
|
2
|
+
|
|
3
|
+
Data does not choose seeds; the coordinating code supplies them and Data
|
|
4
|
+
records them. Provenance holds enough to trace an item back to its source,
|
|
5
|
+
or to make it again: the source and its settings, the collection and
|
|
6
|
+
sampler, the parameters it was generated with, and its seed or position.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import dataclasses
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from ..core._declarations import check_identifier, check_int, keyed
|
|
15
|
+
from ..core._plain import plain_copy
|
|
16
|
+
from ..core.errors import Problem
|
|
17
|
+
|
|
18
|
+
__all__ = ["Provenance"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
22
|
+
class Provenance:
|
|
23
|
+
"""Where an item came from: enough to trace it, or to make it again.
|
|
24
|
+
|
|
25
|
+
Attributes:
|
|
26
|
+
source: The name of the source, such as the task's registered name
|
|
27
|
+
or the name of a published dataset.
|
|
28
|
+
source_settings: The source's settings, such as the task's, as
|
|
29
|
+
plain values: ``settings_to_dict(task.config)``.
|
|
30
|
+
collection: Optional. The name of the collection the item belongs
|
|
31
|
+
to.
|
|
32
|
+
sampler: Optional. The name of the sampler that selected the item.
|
|
33
|
+
sampler_settings: The sampler's settings, as plain values, given
|
|
34
|
+
only with a sampler.
|
|
35
|
+
params: The parameters a generated item was made with, as passed to
|
|
36
|
+
the task's ``generate``. A stateful sampler may choose them
|
|
37
|
+
differently later, so they are kept as they were.
|
|
38
|
+
seed: The seed the item was drawn or generated with.
|
|
39
|
+
position: The item's position: its index in an indexable source, or
|
|
40
|
+
its place in a stream.
|
|
41
|
+
|
|
42
|
+
At least one of ``seed`` and ``position`` is required. Every value is
|
|
43
|
+
plain (``None``, booleans, numbers, strings, lists, and mappings with
|
|
44
|
+
string keys), so provenance can be stored whatever codec the payloads
|
|
45
|
+
use. As with ``settings_to_dict``, tuples become lists.
|
|
46
|
+
|
|
47
|
+
For example, the instance a generated task makes with
|
|
48
|
+
``task.generate(params=params, seed=seed)`` is made again by building
|
|
49
|
+
the same task from ``source`` and ``source_settings`` and calling it
|
|
50
|
+
with the same ``params`` and ``seed``.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
source: str
|
|
54
|
+
source_settings: Mapping[str, Any] = field(default_factory=dict)
|
|
55
|
+
collection: str | None = None
|
|
56
|
+
sampler: str | None = None
|
|
57
|
+
sampler_settings: Mapping[str, Any] = field(default_factory=dict)
|
|
58
|
+
params: Mapping[str, Any] = field(default_factory=dict)
|
|
59
|
+
seed: int | None = None
|
|
60
|
+
position: int | None = None
|
|
61
|
+
|
|
62
|
+
def __post_init__(self) -> None:
|
|
63
|
+
set_ = object.__setattr__
|
|
64
|
+
check_identifier(self.source, "source")
|
|
65
|
+
for name in ("collection", "sampler"):
|
|
66
|
+
if getattr(self, name) is not None:
|
|
67
|
+
check_identifier(getattr(self, name), name)
|
|
68
|
+
for name in ("source_settings", "sampler_settings", "params"):
|
|
69
|
+
set_(self, name, _plain_mapping(getattr(self, name), name))
|
|
70
|
+
if self.sampler_settings and self.sampler is None:
|
|
71
|
+
raise ValueError("sampler_settings were given without a sampler; name the sampler")
|
|
72
|
+
|
|
73
|
+
if self.seed is None and self.position is None:
|
|
74
|
+
raise ValueError(
|
|
75
|
+
"provenance needs a seed or a position (or both), so the item can be "
|
|
76
|
+
"traced or made again"
|
|
77
|
+
)
|
|
78
|
+
if self.seed is not None:
|
|
79
|
+
check_int(self.seed, "seed")
|
|
80
|
+
if self.position is not None:
|
|
81
|
+
check_int(self.position, "position", minimum=0)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _plain_mapping(value: object, what: str) -> dict[str, Any]:
|
|
85
|
+
if dataclasses.is_dataclass(value) and not isinstance(value, type):
|
|
86
|
+
raise TypeError(
|
|
87
|
+
f"{what} must be a mapping of plain values; turn a settings instance into "
|
|
88
|
+
f"one with settings_to_dict(), got {type(value).__name__}"
|
|
89
|
+
)
|
|
90
|
+
problems: list[Problem] = []
|
|
91
|
+
plain: dict[str, Any] = plain_copy(keyed(value, what, "names"), what, problems)
|
|
92
|
+
if problems:
|
|
93
|
+
raise TypeError("provenance holds plain values only: " + "; ".join(map(str, problems)))
|
|
94
|
+
return plain
|