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/data/records.py
ADDED
|
@@ -0,0 +1,546 @@
|
|
|
1
|
+
"""Records: the log of one attempt at one instance.
|
|
2
|
+
|
|
3
|
+
SSAPling fixes the structure of a record, so that Data, Train, and Evaluate
|
|
4
|
+
can handle any project's records. What the payloads contain (observations,
|
|
5
|
+
actions, predictions, teacher contributions, diagnostics) is downstream:
|
|
6
|
+
they pass through uninterpreted.
|
|
7
|
+
|
|
8
|
+
A record has a header, fixed when the attempt starts; steps, one per
|
|
9
|
+
environment step or, in static solving, one per presentation; and a
|
|
10
|
+
summary, saying how the attempt ended. A step holds the environment's
|
|
11
|
+
``StepResult`` and the teachers' ``TeacherResponse`` objects themselves
|
|
12
|
+
rather than copying their fields, so each shape is defined once.
|
|
13
|
+
``RecordBuilder`` builds a record by appending steps, and a record is valid
|
|
14
|
+
before it has a summary, so it can be streamed during interaction and kept
|
|
15
|
+
when an episode is interrupted.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from collections.abc import Mapping, Sequence
|
|
19
|
+
from dataclasses import dataclass, field
|
|
20
|
+
from typing import Any, Literal
|
|
21
|
+
|
|
22
|
+
from ..core._declarations import check_identifier, check_int, keyed, names
|
|
23
|
+
from ..environments.types import ResetResult, StepResult
|
|
24
|
+
from ..teachers.types import TeacherResponse
|
|
25
|
+
from .provenance import Provenance
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"RECORD_SCHEMA_VERSION",
|
|
29
|
+
"AgentTiming",
|
|
30
|
+
"Clock",
|
|
31
|
+
"LateOutput",
|
|
32
|
+
"Record",
|
|
33
|
+
"RecordBuilder",
|
|
34
|
+
"RecordHeader",
|
|
35
|
+
"RecordStatus",
|
|
36
|
+
"RecordStep",
|
|
37
|
+
"RecordSummary",
|
|
38
|
+
"TeacherPlacement",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
RECORD_SCHEMA_VERSION = 1
|
|
42
|
+
"""The version of the record structure this SSAPling writes and reads.
|
|
43
|
+
|
|
44
|
+
It changes when the structure does, so stored records can be recognised and
|
|
45
|
+
read back correctly.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
Clock = Literal["simulated", "wall"]
|
|
49
|
+
"""The clock an attempt was timed with.
|
|
50
|
+
|
|
51
|
+
``simulated``: advanced only by the coordinating code, so runs are
|
|
52
|
+
reproducible and time is counted in model steps. ``wall``: real time, in
|
|
53
|
+
seconds, for real-time and remote environments.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
TeacherPlacement = Literal["coordinator", "environment", "participant"]
|
|
57
|
+
"""Where the teacher sat during an attempt.
|
|
58
|
+
|
|
59
|
+
``coordinator``: the coordinating code consulted it between the model and
|
|
60
|
+
the environment. ``environment``: the environment owned it and reported its
|
|
61
|
+
responses in its transition results. ``participant``: it controlled a
|
|
62
|
+
participant through the ordinary agent interface.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
LateOutput = Literal["discarded", "used"]
|
|
66
|
+
"""What happened to an output that arrived after its deadline.
|
|
67
|
+
|
|
68
|
+
``discarded``: thrown away, and the agent waited for the answer to its
|
|
69
|
+
latest observation. ``used``: used as the agent's action at its next turn.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
RecordStatus = Literal["terminated", "truncated", "failed"]
|
|
73
|
+
"""How an attempt ended.
|
|
74
|
+
|
|
75
|
+
``terminated``: the episode reached a terminal state (won, lost, solved).
|
|
76
|
+
``truncated``: it was cut off before one, for example by a step limit.
|
|
77
|
+
``failed``: it could not continue, for example because a remote environment
|
|
78
|
+
could not be reached.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
_CLOCKS: tuple[Clock, ...] = ("simulated", "wall")
|
|
82
|
+
_PLACEMENTS: tuple[TeacherPlacement, ...] = ("coordinator", "environment", "participant")
|
|
83
|
+
_LATE: tuple[LateOutput, ...] = ("discarded", "used")
|
|
84
|
+
_STATUSES: tuple[RecordStatus, ...] = ("terminated", "truncated", "failed")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
88
|
+
class RecordHeader:
|
|
89
|
+
"""What is fixed when an attempt starts.
|
|
90
|
+
|
|
91
|
+
Attributes:
|
|
92
|
+
id: Identifies the record, so results and storage can refer to it.
|
|
93
|
+
The coordinating code chooses it, for example the episode id.
|
|
94
|
+
instance_id: The id of the instance attempted. The record refers to
|
|
95
|
+
the instance rather than holding it, so the instance's
|
|
96
|
+
reference never travels with its records.
|
|
97
|
+
participants: The agent ids taking part, including any participant
|
|
98
|
+
a teacher controls.
|
|
99
|
+
reset: The environment's ``ResetResult``, holding each participant's
|
|
100
|
+
initial observation. ``None`` for static solving, which has no
|
|
101
|
+
environment.
|
|
102
|
+
provenance: Optional. Where the instance came from.
|
|
103
|
+
seeds: The seeds the coordinating code used, keyed by name, such as
|
|
104
|
+
``{"reset": 7, "model": 3}``.
|
|
105
|
+
clock: The clock the attempt was timed with, ``"simulated"`` or
|
|
106
|
+
``"wall"``. ``None`` when no timing was applied, as in a record
|
|
107
|
+
built by hand or a teacher's demonstration.
|
|
108
|
+
teacher_placement: Where the teacher sat: ``"coordinator"``,
|
|
109
|
+
``"environment"``, or ``"participant"``. ``None`` when there was
|
|
110
|
+
no teacher.
|
|
111
|
+
metadata: Downstream fields, keyed by name, passed through
|
|
112
|
+
uninterpreted.
|
|
113
|
+
schema_version: The version of the record structure. Defaults to
|
|
114
|
+
the one this SSAPling writes.
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
id: str
|
|
118
|
+
instance_id: str
|
|
119
|
+
participants: tuple[str, ...]
|
|
120
|
+
reset: ResetResult | None = None
|
|
121
|
+
provenance: Provenance | None = None
|
|
122
|
+
seeds: Mapping[str, int] = field(default_factory=dict)
|
|
123
|
+
clock: Clock | None = None
|
|
124
|
+
teacher_placement: TeacherPlacement | None = None
|
|
125
|
+
metadata: Mapping[str, Any] = field(default_factory=dict)
|
|
126
|
+
schema_version: int = RECORD_SCHEMA_VERSION
|
|
127
|
+
|
|
128
|
+
def __post_init__(self) -> None:
|
|
129
|
+
set_ = object.__setattr__
|
|
130
|
+
check_identifier(self.id, "a record id")
|
|
131
|
+
check_identifier(self.instance_id, "an instance id")
|
|
132
|
+
participants = _agent_ids(self.participants, "participants")
|
|
133
|
+
if not participants:
|
|
134
|
+
raise ValueError("participants must name at least one agent id")
|
|
135
|
+
set_(self, "participants", participants)
|
|
136
|
+
|
|
137
|
+
if self.reset is not None and not isinstance(self.reset, ResetResult):
|
|
138
|
+
raise TypeError(f"reset must be a ResetResult or None, got {self.reset!r}")
|
|
139
|
+
if self.provenance is not None and not isinstance(self.provenance, Provenance):
|
|
140
|
+
raise TypeError(f"provenance must be a Provenance or None, got {self.provenance!r}")
|
|
141
|
+
seeds = keyed(self.seeds, "seeds", "names")
|
|
142
|
+
for name, seed in seeds.items():
|
|
143
|
+
check_int(seed, f"seeds[{name!r}]")
|
|
144
|
+
set_(self, "seeds", seeds)
|
|
145
|
+
set_(self, "metadata", keyed(self.metadata, "metadata", "names"))
|
|
146
|
+
|
|
147
|
+
_check_choice(self.clock, _CLOCKS, "clock")
|
|
148
|
+
_check_choice(self.teacher_placement, _PLACEMENTS, "teacher_placement")
|
|
149
|
+
if self.static and self.teacher_placement == "environment":
|
|
150
|
+
raise ValueError(
|
|
151
|
+
"teacher_placement is 'environment', but static solving (no reset) has no "
|
|
152
|
+
"environment to hold the teacher"
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
check_int(self.schema_version, "schema_version", minimum=1)
|
|
156
|
+
if self.schema_version > RECORD_SCHEMA_VERSION:
|
|
157
|
+
raise ValueError(
|
|
158
|
+
f"record {self.id!r} has schema version {self.schema_version}, but this "
|
|
159
|
+
f"version of SSAPling reads up to {RECORD_SCHEMA_VERSION}; upgrade SSAPling "
|
|
160
|
+
"to read it"
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
@property
|
|
164
|
+
def static(self) -> bool:
|
|
165
|
+
"""Whether the attempt is static solving: no environment, so no reset."""
|
|
166
|
+
return self.reset is None
|
|
167
|
+
|
|
168
|
+
@property
|
|
169
|
+
def initial_observations(self) -> Mapping[str, Any]:
|
|
170
|
+
"""Each participant's initial observation, keyed by agent id; empty for static solving."""
|
|
171
|
+
return self.reset.observations if self.reset is not None else {}
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
175
|
+
class AgentTiming:
|
|
176
|
+
"""How long one agent took to act at one step, and what timing changed.
|
|
177
|
+
|
|
178
|
+
Attributes:
|
|
179
|
+
elapsed: From perceiving the observation to the output: calls to
|
|
180
|
+
the model's ``advance`` on the simulated clock, seconds on the
|
|
181
|
+
wall clock. The whole time allowed, when no output came in time.
|
|
182
|
+
defaulted: No output came in time. The agent's default action was
|
|
183
|
+
executed or, without one, it was left out of the step, so the
|
|
184
|
+
environment applied its own. In static solving: no prediction.
|
|
185
|
+
late: An output that answered an earlier observation arrived at
|
|
186
|
+
this step: ``"discarded"`` or ``"used"`` (see ``LateOutput``).
|
|
187
|
+
``None`` when there was none.
|
|
188
|
+
"""
|
|
189
|
+
|
|
190
|
+
elapsed: float
|
|
191
|
+
defaulted: bool = False
|
|
192
|
+
late: LateOutput | None = None
|
|
193
|
+
|
|
194
|
+
def __post_init__(self) -> None:
|
|
195
|
+
elapsed = self.elapsed
|
|
196
|
+
if isinstance(elapsed, bool) or not isinstance(elapsed, int | float) or not elapsed >= 0:
|
|
197
|
+
raise ValueError(f"elapsed must be a number, 0 or more, got {elapsed!r}")
|
|
198
|
+
if not isinstance(self.defaulted, bool):
|
|
199
|
+
raise TypeError(f"defaulted must be True or False, got {self.defaulted!r}")
|
|
200
|
+
_check_choice(self.late, _LATE, "late")
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
204
|
+
class RecordStep:
|
|
205
|
+
"""One step of an attempt: one environment step, or one presentation in static solving.
|
|
206
|
+
|
|
207
|
+
Attributes:
|
|
208
|
+
index: The step's position in the record, counting from 0.
|
|
209
|
+
acting: The agent ids that acted at this step.
|
|
210
|
+
proposals: The actions the acting agents proposed, keyed by agent id.
|
|
211
|
+
Interactive steps only.
|
|
212
|
+
teacher_responses: The teacher's responses made during this step.
|
|
213
|
+
executed_actions: The actions actually executed, keyed by agent id.
|
|
214
|
+
Interactive steps only.
|
|
215
|
+
transition: The environment's ``StepResult``. ``None`` for static
|
|
216
|
+
solving, or when the step did not complete, for example because
|
|
217
|
+
the environment could not be reached.
|
|
218
|
+
presented: What each agent was shown, keyed by agent id. Static
|
|
219
|
+
solving only: there, the presentation is the observation.
|
|
220
|
+
predictions: What each agent predicted, keyed by agent id. Static
|
|
221
|
+
solving only.
|
|
222
|
+
timing: How long each acting agent took, and what timing changed,
|
|
223
|
+
keyed by agent id. Empty when no timing was applied.
|
|
224
|
+
diagnostics: What each acting agent's model reported about its
|
|
225
|
+
decision, such as the tokens or compute it used, keyed by agent
|
|
226
|
+
id and passed through uninterpreted. The environment's own
|
|
227
|
+
diagnostics are in ``transition.info``.
|
|
228
|
+
metadata: Downstream fields, keyed by name, passed through
|
|
229
|
+
uninterpreted.
|
|
230
|
+
|
|
231
|
+
``proposals``, ``presented``, ``predictions``, ``timing`` and
|
|
232
|
+
``diagnostics`` may only name agents in ``acting``.
|
|
233
|
+
|
|
234
|
+
``executed_actions`` and ``teacher_responses`` are the same whatever the
|
|
235
|
+
teacher's placement, so code that reads records never needs to know
|
|
236
|
+
where the teacher sat. When the environment reports them in its
|
|
237
|
+
transition result, as it does when it owns the teacher, the coordinating
|
|
238
|
+
code passes the environment's report on here unchanged.
|
|
239
|
+
"""
|
|
240
|
+
|
|
241
|
+
index: int
|
|
242
|
+
acting: tuple[str, ...]
|
|
243
|
+
proposals: Mapping[str, Any] = field(default_factory=dict)
|
|
244
|
+
teacher_responses: Sequence[TeacherResponse] = ()
|
|
245
|
+
executed_actions: Mapping[str, Any] | None = None
|
|
246
|
+
transition: StepResult | None = None
|
|
247
|
+
presented: Mapping[str, Any] | None = None
|
|
248
|
+
predictions: Mapping[str, Any] | None = None
|
|
249
|
+
timing: Mapping[str, AgentTiming] = field(default_factory=dict)
|
|
250
|
+
diagnostics: Mapping[str, Any] = field(default_factory=dict)
|
|
251
|
+
metadata: Mapping[str, Any] = field(default_factory=dict)
|
|
252
|
+
|
|
253
|
+
def __post_init__(self) -> None:
|
|
254
|
+
set_ = object.__setattr__
|
|
255
|
+
check_int(self.index, "index", minimum=0)
|
|
256
|
+
set_(self, "acting", _agent_ids(self.acting, "acting"))
|
|
257
|
+
if self.transition is not None and not isinstance(self.transition, StepResult):
|
|
258
|
+
raise TypeError(f"transition must be a StepResult or None, got {self.transition!r}")
|
|
259
|
+
|
|
260
|
+
set_(self, "proposals", self._by_acting(self.proposals, "proposals"))
|
|
261
|
+
for name in ("presented", "predictions"):
|
|
262
|
+
value = getattr(self, name)
|
|
263
|
+
if value is not None:
|
|
264
|
+
set_(self, name, self._by_acting(value, name))
|
|
265
|
+
if self.executed_actions is not None:
|
|
266
|
+
# Not checked against acting: they may be the environment's report.
|
|
267
|
+
set_(self, "executed_actions", _per_agent(self.executed_actions, "executed_actions"))
|
|
268
|
+
set_(self, "teacher_responses", _responses(self.teacher_responses))
|
|
269
|
+
set_(self, "timing", self._by_acting(self.timing, "timing"))
|
|
270
|
+
if any(not isinstance(timing, AgentTiming) for timing in self.timing.values()):
|
|
271
|
+
raise TypeError("timing must hold only AgentTiming objects")
|
|
272
|
+
set_(self, "diagnostics", self._by_acting(self.diagnostics, "diagnostics"))
|
|
273
|
+
set_(self, "metadata", keyed(self.metadata, "metadata", "names"))
|
|
274
|
+
|
|
275
|
+
def _by_acting(self, value: object, what: str) -> dict[str, Any]:
|
|
276
|
+
"""``value`` keyed by agent id, naming only agents that acted at this step."""
|
|
277
|
+
per_agent = _per_agent(value, what)
|
|
278
|
+
others = [agent for agent in per_agent if agent not in self.acting]
|
|
279
|
+
if others:
|
|
280
|
+
raise ValueError(
|
|
281
|
+
f"step {self.index}: {what} names {_listed(others)}, which did not act "
|
|
282
|
+
f"(acting: {_listed(self.acting) or 'none'})"
|
|
283
|
+
)
|
|
284
|
+
return per_agent
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
288
|
+
class RecordSummary:
|
|
289
|
+
"""How an attempt ended.
|
|
290
|
+
|
|
291
|
+
Attributes:
|
|
292
|
+
status: ``"terminated"``, ``"truncated"``, or ``"failed"`` (see
|
|
293
|
+
``RecordStatus``).
|
|
294
|
+
detail: Optional. Why: for example which limit truncated the
|
|
295
|
+
attempt, or the error that made it fail.
|
|
296
|
+
metadata: Downstream fields, keyed by name, such as counts kept as a
|
|
297
|
+
shortcut for filtering stored records.
|
|
298
|
+
|
|
299
|
+
Build one with ``RecordSummary.terminated()``, ``.truncated()``, or
|
|
300
|
+
``.failed(reason)``.
|
|
301
|
+
"""
|
|
302
|
+
|
|
303
|
+
status: RecordStatus
|
|
304
|
+
detail: Any = None
|
|
305
|
+
metadata: Mapping[str, Any] = field(default_factory=dict)
|
|
306
|
+
|
|
307
|
+
def __post_init__(self) -> None:
|
|
308
|
+
if self.status not in _STATUSES:
|
|
309
|
+
allowed = ", ".join(repr(status) for status in _STATUSES)
|
|
310
|
+
raise ValueError(f"status must be one of {allowed}; got {self.status!r}")
|
|
311
|
+
object.__setattr__(self, "metadata", keyed(self.metadata, "metadata", "names"))
|
|
312
|
+
|
|
313
|
+
@classmethod
|
|
314
|
+
def terminated(
|
|
315
|
+
cls, detail: Any = None, *, metadata: Mapping[str, Any] | None = None
|
|
316
|
+
) -> "RecordSummary":
|
|
317
|
+
"""The episode reached a terminal state."""
|
|
318
|
+
return cls(status="terminated", detail=detail, metadata=metadata or {})
|
|
319
|
+
|
|
320
|
+
@classmethod
|
|
321
|
+
def truncated(
|
|
322
|
+
cls, detail: Any = None, *, metadata: Mapping[str, Any] | None = None
|
|
323
|
+
) -> "RecordSummary":
|
|
324
|
+
"""The episode was cut off before a terminal state; ``detail`` may say by what."""
|
|
325
|
+
return cls(status="truncated", detail=detail, metadata=metadata or {})
|
|
326
|
+
|
|
327
|
+
@classmethod
|
|
328
|
+
def failed(
|
|
329
|
+
cls, reason: Any = None, *, metadata: Mapping[str, Any] | None = None
|
|
330
|
+
) -> "RecordSummary":
|
|
331
|
+
"""The attempt could not continue; ``reason`` says why and is kept in ``detail``."""
|
|
332
|
+
return cls(status="failed", detail=reason, metadata=metadata or {})
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
336
|
+
class Record:
|
|
337
|
+
"""The log of one attempt at one instance.
|
|
338
|
+
|
|
339
|
+
Attributes:
|
|
340
|
+
header: What was fixed when the attempt started.
|
|
341
|
+
steps: The steps so far, in order.
|
|
342
|
+
summary: How the attempt ended; ``None`` while it is under way or
|
|
343
|
+
when it was interrupted. A record is valid without one.
|
|
344
|
+
|
|
345
|
+
A record is checked as a whole when it is made, by the same rules
|
|
346
|
+
``RecordBuilder`` applies as it goes (see ``RecordBuilder.append``).
|
|
347
|
+
"""
|
|
348
|
+
|
|
349
|
+
header: RecordHeader
|
|
350
|
+
steps: tuple[RecordStep, ...] = ()
|
|
351
|
+
summary: RecordSummary | None = None
|
|
352
|
+
|
|
353
|
+
def __post_init__(self) -> None:
|
|
354
|
+
if not isinstance(self.header, RecordHeader):
|
|
355
|
+
raise TypeError(f"header must be a RecordHeader, got {self.header!r}")
|
|
356
|
+
if isinstance(self.steps, Mapping) or not isinstance(self.steps, Sequence):
|
|
357
|
+
raise TypeError(f"steps must be a sequence of RecordStep, got {self.steps!r}")
|
|
358
|
+
steps = tuple(self.steps)
|
|
359
|
+
for position, step in enumerate(steps):
|
|
360
|
+
_check_step(self.header, step, position, steps[position - 1] if position else None)
|
|
361
|
+
object.__setattr__(self, "steps", steps)
|
|
362
|
+
if self.summary is not None and not isinstance(self.summary, RecordSummary):
|
|
363
|
+
raise TypeError(f"summary must be a RecordSummary or None, got {self.summary!r}")
|
|
364
|
+
|
|
365
|
+
@property
|
|
366
|
+
def finished(self) -> bool:
|
|
367
|
+
"""Whether the record has a summary."""
|
|
368
|
+
return self.summary is not None
|
|
369
|
+
|
|
370
|
+
@classmethod
|
|
371
|
+
def _from_checked(
|
|
372
|
+
cls, header: RecordHeader, steps: tuple[RecordStep, ...], summary: RecordSummary | None
|
|
373
|
+
) -> "Record":
|
|
374
|
+
"""A record from parts the builder has already checked, without checking them again."""
|
|
375
|
+
record = object.__new__(cls)
|
|
376
|
+
object.__setattr__(record, "header", header)
|
|
377
|
+
object.__setattr__(record, "steps", steps)
|
|
378
|
+
object.__setattr__(record, "summary", summary)
|
|
379
|
+
return record
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
class RecordBuilder:
|
|
383
|
+
"""Builds a record step by step.
|
|
384
|
+
|
|
385
|
+
Example::
|
|
386
|
+
|
|
387
|
+
builder = RecordBuilder(header)
|
|
388
|
+
builder.append(RecordStep(index=0, acting=("student",),
|
|
389
|
+
proposals={"student": "2"}, transition=result))
|
|
390
|
+
builder.record # a Record so far: valid, with no summary yet
|
|
391
|
+
builder.finish(RecordSummary.terminated())
|
|
392
|
+
|
|
393
|
+
Each step is checked as it is appended, so a mistake is reported where
|
|
394
|
+
it is made. ``record`` can be read at any time, for example to stream
|
|
395
|
+
the attempt or to learn from it online.
|
|
396
|
+
"""
|
|
397
|
+
|
|
398
|
+
def __init__(self, header: RecordHeader) -> None:
|
|
399
|
+
if not isinstance(header, RecordHeader):
|
|
400
|
+
raise TypeError(f"header must be a RecordHeader, got {header!r}")
|
|
401
|
+
self._header = header
|
|
402
|
+
self._steps: list[RecordStep] = []
|
|
403
|
+
self._summary: RecordSummary | None = None
|
|
404
|
+
self._record: Record | None = None
|
|
405
|
+
|
|
406
|
+
@property
|
|
407
|
+
def header(self) -> RecordHeader:
|
|
408
|
+
"""The record's header."""
|
|
409
|
+
return self._header
|
|
410
|
+
|
|
411
|
+
@property
|
|
412
|
+
def next_index(self) -> int:
|
|
413
|
+
"""The index the next appended step must have."""
|
|
414
|
+
return len(self._steps)
|
|
415
|
+
|
|
416
|
+
@property
|
|
417
|
+
def finished(self) -> bool:
|
|
418
|
+
"""Whether ``finish`` has been called."""
|
|
419
|
+
return self._summary is not None
|
|
420
|
+
|
|
421
|
+
@property
|
|
422
|
+
def record(self) -> Record:
|
|
423
|
+
"""The record so far. Its ``summary`` is ``None`` until ``finish`` is called."""
|
|
424
|
+
if self._record is None:
|
|
425
|
+
self._record = Record._from_checked(self._header, tuple(self._steps), self._summary)
|
|
426
|
+
return self._record
|
|
427
|
+
|
|
428
|
+
def append(self, step: RecordStep) -> None:
|
|
429
|
+
"""Add the next step.
|
|
430
|
+
|
|
431
|
+
Raises:
|
|
432
|
+
TypeError: ``step`` is not a ``RecordStep``.
|
|
433
|
+
ValueError: The record is finished; the step's index is not
|
|
434
|
+
``next_index``; it names an agent that is not a participant;
|
|
435
|
+
it does not fit the record's kind (a static record's steps
|
|
436
|
+
have presentations and predictions, an interactive record's
|
|
437
|
+
have proposals, executed actions and transitions); or the
|
|
438
|
+
environment ended the episode at the previous step.
|
|
439
|
+
"""
|
|
440
|
+
if self.finished:
|
|
441
|
+
raise ValueError(
|
|
442
|
+
f"record {self._header.id!r} is finished; a finished record takes no more steps"
|
|
443
|
+
)
|
|
444
|
+
_check_step(self._header, step, self.next_index, self._steps[-1] if self._steps else None)
|
|
445
|
+
self._steps.append(step)
|
|
446
|
+
self._record = None
|
|
447
|
+
|
|
448
|
+
def finish(self, summary: RecordSummary) -> Record:
|
|
449
|
+
"""Say how the attempt ended, and return the finished record.
|
|
450
|
+
|
|
451
|
+
Raises:
|
|
452
|
+
TypeError: ``summary`` is not a ``RecordSummary``.
|
|
453
|
+
ValueError: The record is already finished.
|
|
454
|
+
"""
|
|
455
|
+
if not isinstance(summary, RecordSummary):
|
|
456
|
+
raise TypeError(f"summary must be a RecordSummary, got {summary!r}")
|
|
457
|
+
if self.finished:
|
|
458
|
+
raise ValueError(f"record {self._header.id!r} is already finished")
|
|
459
|
+
self._summary = summary
|
|
460
|
+
self._record = None
|
|
461
|
+
return self.record
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _check_step(
|
|
465
|
+
header: RecordHeader, step: object, position: int, previous: RecordStep | None
|
|
466
|
+
) -> None:
|
|
467
|
+
"""Check that ``step`` fits ``header`` as the step at ``position``, after ``previous``."""
|
|
468
|
+
if not isinstance(step, RecordStep):
|
|
469
|
+
raise TypeError(f"a record's steps must be RecordStep objects, got {step!r}")
|
|
470
|
+
if step.index != position:
|
|
471
|
+
raise ValueError(f"step index {step.index} is out of order: the next step is {position}")
|
|
472
|
+
at = f"step {step.index}"
|
|
473
|
+
strangers = [agent for agent in step.acting if agent not in header.participants]
|
|
474
|
+
if strangers:
|
|
475
|
+
raise ValueError(
|
|
476
|
+
f"{at}: {_listed(strangers)} acted but not among the participants "
|
|
477
|
+
f"({_listed(header.participants)})"
|
|
478
|
+
)
|
|
479
|
+
if (
|
|
480
|
+
previous is not None
|
|
481
|
+
and previous.transition is not None
|
|
482
|
+
and previous.transition.episode_over
|
|
483
|
+
):
|
|
484
|
+
raise ValueError(
|
|
485
|
+
f"{at}: the environment ended the episode at step {previous.index}; a record "
|
|
486
|
+
"holds one attempt, so start a new record for the next episode"
|
|
487
|
+
)
|
|
488
|
+
|
|
489
|
+
if header.static:
|
|
490
|
+
mixed = [
|
|
491
|
+
name
|
|
492
|
+
for name, present in (
|
|
493
|
+
("proposals", bool(step.proposals)),
|
|
494
|
+
("executed_actions", step.executed_actions is not None),
|
|
495
|
+
("transition", step.transition is not None),
|
|
496
|
+
)
|
|
497
|
+
if present
|
|
498
|
+
]
|
|
499
|
+
if mixed:
|
|
500
|
+
raise ValueError(
|
|
501
|
+
f"{at} has {', '.join(mixed)}, but record {header.id!r} is static solving (its "
|
|
502
|
+
"header has no reset): its steps hold presentations and predictions"
|
|
503
|
+
)
|
|
504
|
+
else:
|
|
505
|
+
mixed = [name for name in ("presented", "predictions") if getattr(step, name) is not None]
|
|
506
|
+
if mixed:
|
|
507
|
+
raise ValueError(
|
|
508
|
+
f"{at} has {', '.join(mixed)}, but record {header.id!r} is interactive (its "
|
|
509
|
+
"header has a reset): its steps hold proposals, executed actions and "
|
|
510
|
+
"transitions"
|
|
511
|
+
)
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def _per_agent(value: object, what: str) -> dict[str, Any]:
|
|
515
|
+
if not isinstance(value, Mapping):
|
|
516
|
+
raise TypeError(
|
|
517
|
+
f"{what} must be keyed by agent id, even with one agent, such as "
|
|
518
|
+
f"{{'agent': ...}}, got {value!r}"
|
|
519
|
+
)
|
|
520
|
+
return keyed(value, what, "agent ids")
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def _agent_ids(value: object, what: str) -> tuple[str, ...]:
|
|
524
|
+
ids = names(value, what, of="agent ids", example="('student',)")
|
|
525
|
+
repeated = sorted({agent for agent in ids if ids.count(agent) > 1})
|
|
526
|
+
if repeated:
|
|
527
|
+
raise ValueError(f"{what} names {_listed(repeated)} more than once")
|
|
528
|
+
return ids
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def _responses(value: object) -> tuple[TeacherResponse, ...]:
|
|
532
|
+
if isinstance(value, Mapping) or not isinstance(value, Sequence):
|
|
533
|
+
raise TypeError(f"teacher_responses must be a sequence of TeacherResponse, got {value!r}")
|
|
534
|
+
if any(not isinstance(response, TeacherResponse) for response in value):
|
|
535
|
+
raise TypeError("teacher_responses must contain only TeacherResponse objects")
|
|
536
|
+
return tuple(value)
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def _check_choice(value: object, allowed: tuple[str, ...], what: str) -> None:
|
|
540
|
+
if value is not None and value not in allowed:
|
|
541
|
+
choices = ", ".join(repr(choice) for choice in allowed)
|
|
542
|
+
raise ValueError(f"{what} must be one of {choices}, or None; got {value!r}")
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def _listed(agents: Sequence[str]) -> str:
|
|
546
|
+
return ", ".join(repr(agent) for agent in agents)
|