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,339 @@
1
+ """Sources and samplers: where instances come from, and how they are picked.
2
+
3
+ A **source** is anything that offers instances the way a task does: by
4
+ generating them (the task feature ``"generate"``: ``generate(params,
5
+ seed)``) or by listing them (the task feature ``"enumerate"``: ``ids()``
6
+ and ``get(id)``). A task is a source; so is a stored collection, a teacher
7
+ proposing problems, or a service supplying identifiers, once it offers one
8
+ of those methods. ``tasks.supports(source, feature)`` says which.
9
+
10
+ A **sampler** picks instances from a source according to its settings.
11
+ ``draw(seed=...)`` returns a ``Sample``: the instance, and what is needed to
12
+ make it again. The same seed and the same settings always give the same
13
+ sample. Samplers are components, registered in ``ssapling.data.samplers``
14
+ and built through Core::
15
+
16
+ sampler = samplers.create("stratified", {"by": "difficulty"}, source=task)
17
+ sample = sampler.draw(seed=7)
18
+ sample.instance
19
+ """
20
+
21
+ import random
22
+ from collections.abc import Callable, Iterable, Mapping
23
+ from dataclasses import dataclass, field
24
+ from typing import Any, Protocol
25
+
26
+ from ..core import Registry, setting, settings_to_dict, validate_settings
27
+ from ..core._declarations import keyed, name_of
28
+ from ..tasks import EnumeratedTask, GeneratedTask, Instance, UnknownInstanceError
29
+ from ..tasks import supports as task_supports
30
+
31
+ __all__ = [
32
+ "GeneratedSampler",
33
+ "GeneratedSettings",
34
+ "Instances",
35
+ "Sample",
36
+ "Sampler",
37
+ "StratifiedSampler",
38
+ "StratifiedSettings",
39
+ "UniformSampler",
40
+ "samplers",
41
+ ]
42
+
43
+
44
+ @dataclass(frozen=True, slots=True, kw_only=True)
45
+ class Sample:
46
+ """One instance a sampler picked, and what is needed to make it again.
47
+
48
+ Attributes:
49
+ instance: The instance.
50
+ params: For a generated source: the parameters ``generate`` was
51
+ called with. Together with the draw's seed, they make the
52
+ instance again even after a stateful sampler has changed.
53
+ position: For an enumerated source: the instance's index in the
54
+ source's ``ids()``.
55
+ """
56
+
57
+ instance: Instance
58
+ params: Mapping[str, Any] = field(default_factory=dict)
59
+ position: int | None = None
60
+
61
+ def __post_init__(self) -> None:
62
+ if not isinstance(self.instance, Instance):
63
+ raise TypeError(f"a sample's instance must be an Instance, got {self.instance!r}")
64
+ object.__setattr__(self, "params", keyed(self.params, "params", "names"))
65
+
66
+
67
+ class Sampler(Protocol):
68
+ """What every sampler provides: one sample per seed.
69
+
70
+ ``draw`` must be reproducible: the same seed, with the same settings and
71
+ state, gives the same sample. A sampler may also have ``source``, the
72
+ source it draws from, which ``Collections`` checks, and
73
+ ``export_state()``/``restore_state(state)`` when it has state that
74
+ changes over time, such as weights a training schedule adjusts.
75
+ """
76
+
77
+ def draw(self, *, seed: int) -> Sample:
78
+ """Pick one instance, using ``seed`` for every random choice."""
79
+ ...
80
+
81
+
82
+ # A listed source
83
+
84
+
85
+ class Instances:
86
+ """A source listing the instances it is given, in their order: an
87
+ enumerated source (``ids()`` and ``get(id)``) for a few instances made in
88
+ code, such as one problem a lesson keeps coming back to.
89
+
90
+ Raises:
91
+ TypeError: Something given isn't an ``Instance``.
92
+ ValueError: Two instances have the same id.
93
+ """
94
+
95
+ def __init__(self, instances: Iterable[Instance]) -> None:
96
+ self._instances: dict[str, Instance] = {}
97
+ for instance in instances:
98
+ if not isinstance(instance, Instance):
99
+ raise TypeError(f"Instances holds Instance objects, got {instance!r}")
100
+ if instance.id in self._instances:
101
+ raise ValueError(f"two instances have the id {instance.id!r}")
102
+ self._instances[instance.id] = instance
103
+
104
+ def ids(self) -> list[str]:
105
+ """Every instance's id, in the order given."""
106
+ return list(self._instances)
107
+
108
+ def get(self, instance_id: str) -> Instance:
109
+ """The instance with ``instance_id``.
110
+
111
+ Raises:
112
+ UnknownInstanceError: None has that id.
113
+ """
114
+ try:
115
+ return self._instances[instance_id]
116
+ except KeyError:
117
+ raise UnknownInstanceError(instance_id, task="Instances") from None
118
+
119
+ def __repr__(self) -> str:
120
+ return f"Instances({self.ids()!r})"
121
+
122
+
123
+ # Built-in samplers
124
+
125
+
126
+ class UniformSampler:
127
+ """Picks any instance of an enumerated source, each equally likely."""
128
+
129
+ def __init__(self, *, source: object) -> None:
130
+ self.source = source
131
+ self._source = _enumerated(source, self)
132
+ self._ids = tuple(self._source.ids())
133
+ if not self._ids:
134
+ raise ValueError(f"{name_of(source)} lists no instances to draw from")
135
+
136
+ def draw(self, *, seed: int) -> Sample:
137
+ """An instance chosen uniformly, by ``seed``."""
138
+ position = random.Random(seed).randrange(len(self._ids))
139
+ return Sample(instance=self._source.get(self._ids[position]), position=position)
140
+
141
+
142
+ @dataclass(frozen=True)
143
+ class StratifiedSettings:
144
+ """Settings for the stratified sampler."""
145
+
146
+ by: str = setting(description="The descriptor whose values are the strata.", min_length=1)
147
+ weights: dict[str, float] = setting(
148
+ default_factory=dict,
149
+ description=(
150
+ "Each stratum's weight, keyed by the descriptor value as a string, such as "
151
+ '{"easy": 1, "hard": 3}. Empty: every stratum equally likely. A stratum left '
152
+ "out is not drawn."
153
+ ),
154
+ )
155
+
156
+ def validate(self) -> None:
157
+ _check_weights(self.weights)
158
+
159
+
160
+ class StratifiedSampler:
161
+ """Picks a stratum (a descriptor value) by weight, then an instance of it uniformly.
162
+
163
+ With equal weights, each stratum is drawn equally often however many
164
+ instances it has. Weights make some strata likelier, or leave some out;
165
+ ``set_weights`` changes them over time, as a curriculum might.
166
+ """
167
+
168
+ Settings = StratifiedSettings
169
+
170
+ def __init__(self, config: StratifiedSettings, *, source: object) -> None:
171
+ self.source = source
172
+ self.config = validate_settings(StratifiedSettings, config) # also when built directly
173
+ enumerated = _enumerated(source, self)
174
+ self._instances = tuple(enumerated.get(instance_id) for instance_id in enumerated.ids())
175
+ self._strata: dict[str, list[int]] = {}
176
+ for position, instance in enumerate(self._instances):
177
+ if config.by not in instance.descriptors:
178
+ raise ValueError(
179
+ f"instance {instance.id!r} has no descriptor {config.by!r} to stratify by"
180
+ )
181
+ self._strata.setdefault(str(instance.descriptors[config.by]), []).append(position)
182
+ if not self._strata:
183
+ raise ValueError(f"{name_of(source)} lists no instances to draw from")
184
+ _check_keys(config.weights, self._strata, f"values of the descriptor {config.by!r}")
185
+
186
+ @property
187
+ def strata(self) -> tuple[str, ...]:
188
+ """The strata, as strings, in the order they first appear in the source."""
189
+ return tuple(self._strata)
190
+
191
+ def draw(self, *, seed: int) -> Sample:
192
+ """A stratum chosen by weight, then one of its instances uniformly, both by ``seed``."""
193
+ rng = random.Random(seed)
194
+ stratum = _choose(rng, self.strata, self.config.weights)
195
+ position = rng.choice(self._strata[stratum])
196
+ return Sample(instance=self._instances[position], position=position)
197
+
198
+ def set_weights(self, weights: Mapping[str, float]) -> None:
199
+ """Replace the strata's weights; ``config`` changes to match."""
200
+ config = _with_weights(self.config, weights)
201
+ _check_keys(config.weights, self._strata, f"values of the descriptor {config.by!r}")
202
+ self.config = config
203
+
204
+ def export_state(self) -> dict[str, Any]:
205
+ """The current weights, for a checkpoint."""
206
+ return {"weights": dict(self.config.weights)}
207
+
208
+ def restore_state(self, state: Mapping[str, Any]) -> None:
209
+ """Return to weights saved by ``export_state``."""
210
+ self.set_weights(state["weights"])
211
+
212
+
213
+ @dataclass(frozen=True)
214
+ class GeneratedSettings:
215
+ """Settings for the generated sampler."""
216
+
217
+ params: dict[str, Any] = setting(
218
+ default_factory=dict, description="Parameters passed to generate on every draw."
219
+ )
220
+ vary: str | None = setting(None, description="A parameter whose value changes per draw.")
221
+ values: list[Any] = setting(default_factory=list, description="The values `vary` takes.")
222
+ weights: dict[str, float] = setting(
223
+ default_factory=dict,
224
+ description=(
225
+ "Each value's weight, keyed by the value as a string, such as "
226
+ '{"1": 1, "3": 2}. Empty: every value equally likely. A value left out is not drawn.'
227
+ ),
228
+ )
229
+
230
+ def validate(self) -> None:
231
+ if self.vary is None:
232
+ if self.values or self.weights:
233
+ raise ValueError("values and weights apply to a varied parameter; set vary")
234
+ return
235
+ if not self.values:
236
+ raise ValueError(f"vary is {self.vary!r}, so values must list what it takes")
237
+ if self.vary in self.params:
238
+ raise ValueError(f"{self.vary!r} is both fixed in params and varied")
239
+ keys = [str(value) for value in self.values]
240
+ if len(set(keys)) != len(keys):
241
+ raise ValueError("values must be distinct as strings, since weights are keyed by them")
242
+ _check_weights(self.weights)
243
+ _check_keys(self.weights, keys, "values")
244
+
245
+
246
+ class GeneratedSampler:
247
+ """Generates instances: fixed parameters, plus one parameter that can vary by weight.
248
+
249
+ For example, ``{"vary": "digits", "values": [1, 2, 3], "weights": {"3":
250
+ 2}}`` asks an addition task for 3-digit problems only, and
251
+ ``set_weights`` can shift it towards longer problems over time.
252
+ """
253
+
254
+ Settings = GeneratedSettings
255
+
256
+ def __init__(self, config: GeneratedSettings | None = None, *, source: object) -> None:
257
+ if not task_supports(source, "generate"):
258
+ raise TypeError(
259
+ f"{name_of(source)} cannot generate instances: the generated sampler needs a "
260
+ "source with generate(params, seed); for a listed source use 'uniform' or "
261
+ "'stratified'"
262
+ )
263
+ self.source = source
264
+ self.config = validate_settings(GeneratedSettings, config) # also when built directly
265
+
266
+ def draw(self, *, seed: int) -> Sample:
267
+ """Generate an instance with ``seed``, choosing the varied parameter by ``seed`` too."""
268
+ params = dict(self.config.params)
269
+ if self.config.vary is not None:
270
+ by_key = {str(value): value for value in self.config.values}
271
+ key = _choose(random.Random(seed), tuple(by_key), self.config.weights)
272
+ params[self.config.vary] = by_key[key]
273
+ source: GeneratedTask = self.source # type: ignore[assignment]
274
+ return Sample(instance=source.generate(params=params, seed=seed), params=params)
275
+
276
+ def set_weights(self, weights: Mapping[str, float]) -> None:
277
+ """Replace the values' weights; ``config`` changes to match."""
278
+ self.config = _with_weights(self.config, weights)
279
+
280
+ def export_state(self) -> dict[str, Any]:
281
+ """The current weights, for a checkpoint."""
282
+ return {"weights": dict(self.config.weights)}
283
+
284
+ def restore_state(self, state: Mapping[str, Any]) -> None:
285
+ """Return to weights saved by ``export_state``."""
286
+ self.set_weights(state["weights"])
287
+
288
+
289
+ samplers: Registry[Callable[..., Sampler]] = Registry("sampler")
290
+ """Registered samplers. Also available as ``ssapling.registries.samplers``.
291
+
292
+ The built-ins are registered here: ``"uniform"``, ``"stratified"`` and
293
+ ``"generated"``. A downstream sampler is registered alongside them.
294
+ """
295
+ samplers.register("uniform", UniformSampler)
296
+ samplers.register("stratified", StratifiedSampler)
297
+ samplers.register("generated", GeneratedSampler)
298
+
299
+
300
+ # Helpers
301
+
302
+
303
+ def _enumerated(source: object, sampler: object) -> EnumeratedTask:
304
+ if not task_supports(source, "enumerate"):
305
+ raise TypeError(
306
+ f"{name_of(source)} does not list its instances: {name_of(sampler)} needs a source "
307
+ "with ids() and get(id); for a generated source use 'generated'"
308
+ )
309
+ return source # type: ignore[return-value]
310
+
311
+
312
+ def _check_weights(weights: Mapping[str, float]) -> None:
313
+ for key, weight in weights.items():
314
+ if not weight >= 0 or weight == float("inf"):
315
+ raise ValueError(f"weights[{key!r}] must be a finite number of 0 or more, got {weight}")
316
+ if weights and not sum(weights.values()) > 0:
317
+ raise ValueError("at least one weight must be more than 0")
318
+
319
+
320
+ def _check_keys(weights: Mapping[str, float], known: Any, what: str) -> None:
321
+ unknown = [key for key in weights if key not in known]
322
+ if unknown:
323
+ raise ValueError(
324
+ f"weights name {', '.join(repr(k) for k in unknown)}, which are not among the "
325
+ f"{what}: {', '.join(repr(k) for k in known)}"
326
+ )
327
+
328
+
329
+ def _choose(rng: random.Random, keys: tuple[str, ...], weights: Mapping[str, float]) -> str:
330
+ """One of ``keys``, by ``weights``; equally likely when there are none."""
331
+ if not weights:
332
+ return rng.choice(keys)
333
+ return rng.choices(keys, weights=[weights.get(key, 0.0) for key in keys])[0]
334
+
335
+
336
+ def _with_weights[S](config: S, weights: Mapping[str, float]) -> S:
337
+ """``config`` with new weights, checked like any settings."""
338
+ values = {**settings_to_dict(config), "weights": dict(weights)}
339
+ return validate_settings(type(config), values)