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,173 @@
|
|
|
1
|
+
"""Aggregation: per-instance values combined into summaries, with exclusions reported.
|
|
2
|
+
|
|
3
|
+
An **aggregator** is a function over a list of values, registered by name in
|
|
4
|
+
``aggregators``; ``"count"`` and ``"mean"`` are built in. An **aggregation**
|
|
5
|
+
names a measurement, an aggregator, and optionally a descriptor to group
|
|
6
|
+
by, the descriptor values an instance must have to count (``where``), and
|
|
7
|
+
how its groups are weighted. The machinery, not the aggregator, decides
|
|
8
|
+
which values contribute:
|
|
9
|
+
|
|
10
|
+
- Only instances that match ``where`` are aggregated. The rest are in no
|
|
11
|
+
count, neither contributed nor excluded.
|
|
12
|
+
- Unavailable and failed values never count, as zero or otherwise. They are
|
|
13
|
+
left out, and how many is reported by reason.
|
|
14
|
+
- Truncated attempts count, since the task scored whatever outcome was
|
|
15
|
+
reached, unless an aggregation excludes them.
|
|
16
|
+
- An aggregate over no values is ``None``, undefined, never 0.
|
|
17
|
+
- With ``weighting="equal"``, the value is the mean of the groups' values,
|
|
18
|
+
each group weighing the same however many instances it holds; a group
|
|
19
|
+
with no value is left out of that mean.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import dataclasses
|
|
23
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from typing import Any, Literal
|
|
26
|
+
|
|
27
|
+
from ..core import Registry, setting, validate_settings
|
|
28
|
+
from ..data._matching import matches
|
|
29
|
+
from .measurement import InstanceResult
|
|
30
|
+
|
|
31
|
+
__all__ = ["AggregationSettings", "Summary", "aggregate", "aggregators"]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class AggregationSettings:
|
|
36
|
+
"""One aggregation: which measurement's values, of which instances, combined how, grouped by
|
|
37
|
+
what, and weighted how."""
|
|
38
|
+
|
|
39
|
+
measurement: str = setting(description="The measurement whose values are combined.")
|
|
40
|
+
aggregator: str = setting(description="The registered aggregator, such as 'mean'.")
|
|
41
|
+
group_by: str | None = setting(
|
|
42
|
+
None, description="A descriptor: also summarise each of its values separately."
|
|
43
|
+
)
|
|
44
|
+
exclude_truncated: bool = setting(
|
|
45
|
+
False, description="Leave out the values of attempts that were truncated."
|
|
46
|
+
)
|
|
47
|
+
where: dict[str, Any] = setting(
|
|
48
|
+
default_factory=dict,
|
|
49
|
+
description=(
|
|
50
|
+
"Descriptor values an instance must have to be aggregated, such as "
|
|
51
|
+
"{'group': 'broad'}. Other instances are in no count."
|
|
52
|
+
),
|
|
53
|
+
)
|
|
54
|
+
weighting: Literal["pooled", "equal"] = setting(
|
|
55
|
+
"pooled",
|
|
56
|
+
description=(
|
|
57
|
+
"'pooled': every instance weighs the same. 'equal': the value is the mean of the "
|
|
58
|
+
"groups' values, every group weighing the same; needs group_by."
|
|
59
|
+
),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
def validate(self) -> None:
|
|
63
|
+
if self.weighting == "equal" and self.group_by is None:
|
|
64
|
+
raise ValueError("weighting 'equal' needs group_by: the groups it weighs equally")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
68
|
+
class Summary:
|
|
69
|
+
"""The result of one aggregation.
|
|
70
|
+
|
|
71
|
+
Attributes:
|
|
72
|
+
value: What the aggregator gave, or ``None`` when no value
|
|
73
|
+
contributed: undefined, not 0. With equal weighting, the mean
|
|
74
|
+
of the groups' values, ``None`` when no group has one.
|
|
75
|
+
contributed: How many values were combined (with equal weighting,
|
|
76
|
+
in all the groups together).
|
|
77
|
+
excluded: How many were left out, by reason: ``"unavailable"``,
|
|
78
|
+
``"failed"``, ``"truncated"``. Reasons with none are omitted.
|
|
79
|
+
Instances that don't match ``where`` are not among them.
|
|
80
|
+
groups: With ``group_by``: a summary for each value of the
|
|
81
|
+
descriptor, keyed by the value as a string. Instances without
|
|
82
|
+
the descriptor are under ``"None"``. Empty otherwise.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
value: Any
|
|
86
|
+
contributed: int
|
|
87
|
+
excluded: Mapping[str, int] = field(default_factory=dict)
|
|
88
|
+
groups: Mapping[str, "Summary"] = field(default_factory=dict)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def aggregate(
|
|
92
|
+
instances: Sequence[InstanceResult],
|
|
93
|
+
aggregations: Mapping[str, AggregationSettings | Mapping[str, Any]],
|
|
94
|
+
) -> dict[str, Summary]:
|
|
95
|
+
"""Combine per-instance values into a summary for each aggregation.
|
|
96
|
+
|
|
97
|
+
It needs only the per-instance results, so aggregates can be recomputed
|
|
98
|
+
from stored results without running the model again.
|
|
99
|
+
|
|
100
|
+
Example::
|
|
101
|
+
|
|
102
|
+
aggregate(results.instances, {"accuracy": {"measurement": "score", "aggregator": "mean"}})
|
|
103
|
+
|
|
104
|
+
Raises:
|
|
105
|
+
ConfigError: An aggregation's settings are invalid.
|
|
106
|
+
UnknownComponentError: An aggregation names no registered aggregator.
|
|
107
|
+
"""
|
|
108
|
+
summaries = {}
|
|
109
|
+
for name, settings in aggregations.items():
|
|
110
|
+
aggregation = validate_settings(AggregationSettings, settings)
|
|
111
|
+
combine = aggregators.get(aggregation.aggregator)
|
|
112
|
+
matching = [r for r in instances if matches(r.descriptors, aggregation.where)]
|
|
113
|
+
summary = _summarise(matching, aggregation, combine)
|
|
114
|
+
if aggregation.group_by is not None:
|
|
115
|
+
groups: dict[str, list[InstanceResult]] = {}
|
|
116
|
+
for result in matching:
|
|
117
|
+
key = str(result.descriptors.get(aggregation.group_by))
|
|
118
|
+
groups.setdefault(key, []).append(result)
|
|
119
|
+
summary = dataclasses.replace(
|
|
120
|
+
summary,
|
|
121
|
+
groups={k: _summarise(rs, aggregation, combine) for k, rs in groups.items()},
|
|
122
|
+
)
|
|
123
|
+
if aggregation.weighting == "equal": # validated: group_by is set
|
|
124
|
+
values = [group.value for group in summary.groups.values() if group.value is not None]
|
|
125
|
+
summary = dataclasses.replace(
|
|
126
|
+
summary, value=sum(values) / len(values) if values else None
|
|
127
|
+
)
|
|
128
|
+
summaries[name] = summary
|
|
129
|
+
return summaries
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _summarise(
|
|
133
|
+
instances: Sequence[InstanceResult],
|
|
134
|
+
aggregation: AggregationSettings,
|
|
135
|
+
combine: Callable[[list[Any]], Any],
|
|
136
|
+
) -> Summary:
|
|
137
|
+
values: list[Any] = []
|
|
138
|
+
excluded: dict[str, int] = {}
|
|
139
|
+
for result in instances:
|
|
140
|
+
measured = result.values[aggregation.measurement]
|
|
141
|
+
reason: str
|
|
142
|
+
if measured.status in ("unavailable", "failed"):
|
|
143
|
+
reason = measured.status
|
|
144
|
+
elif aggregation.exclude_truncated and result.status == "truncated":
|
|
145
|
+
reason = "truncated"
|
|
146
|
+
else:
|
|
147
|
+
values.append(measured.value)
|
|
148
|
+
continue
|
|
149
|
+
excluded[reason] = excluded.get(reason, 0) + 1
|
|
150
|
+
return Summary(
|
|
151
|
+
value=combine(values) if values else None, contributed=len(values), excluded=excluded
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def count(values: list[Any]) -> int:
|
|
156
|
+
"""How many values contributed."""
|
|
157
|
+
return len(values)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def mean(values: list[Any]) -> Any:
|
|
161
|
+
"""The mean of the values, pooled: every instance weighs the same. True counts as 1."""
|
|
162
|
+
return sum(values) / len(values)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
aggregators: Registry[Callable[[list[Any]], Any]] = Registry("aggregator")
|
|
166
|
+
"""Registered aggregators. Also available as ``ssapling.registries.aggregators``.
|
|
167
|
+
|
|
168
|
+
An aggregator is registered as the function itself: it takes the list of
|
|
169
|
+
contributing values, never empty, and returns the aggregate. ``"count"``
|
|
170
|
+
and ``"mean"`` are built in.
|
|
171
|
+
"""
|
|
172
|
+
aggregators.register("count", count)
|
|
173
|
+
aggregators.register("mean", mean)
|
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
"""Assessments: run a model over evaluation collections, measure each instance, aggregate.
|
|
2
|
+
|
|
3
|
+
An **assessment** is a registered component with its own settings. The
|
|
4
|
+
built-in ``"standard"`` assessment is driven entirely by its settings: which
|
|
5
|
+
collections, which measurements, which aggregations, and how each instance
|
|
6
|
+
is attempted. The same assessment runs standalone and inside Train's assess
|
|
7
|
+
stage.
|
|
8
|
+
|
|
9
|
+
assessment = assessments.create(
|
|
10
|
+
"standard",
|
|
11
|
+
{"collections": ["validation"],
|
|
12
|
+
"aggregations": {"accuracy": {"measurement": "score", "aggregator": "mean"}}},
|
|
13
|
+
collections=collections, task=task,
|
|
14
|
+
)
|
|
15
|
+
results = await assessment.run(model, run_id="assess-1", seed=7)
|
|
16
|
+
results.aggregates["accuracy"].value
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import asyncio
|
|
20
|
+
import dataclasses
|
|
21
|
+
import random
|
|
22
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from typing import Any, Protocol
|
|
25
|
+
|
|
26
|
+
from ..core import Registry, setting, settings_to_dict, validate_settings
|
|
27
|
+
from ..core._declarations import check_identifier, check_int, keyed, name_of
|
|
28
|
+
from ..core._execution import Execution
|
|
29
|
+
from ..data import Collections, Drawn, Record, Store
|
|
30
|
+
from ..environments import supports as environment_supports
|
|
31
|
+
from ..interaction import EpisodeSettings, run_episode, solve
|
|
32
|
+
from ..interaction.episode import TeacherContext
|
|
33
|
+
from ..models import supports as model_supports
|
|
34
|
+
from .aggregation import AggregationSettings, Summary, aggregate, aggregators
|
|
35
|
+
from .measurement import InstanceResult, MeasuredValue, Trial, measurements
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"Assessment",
|
|
39
|
+
"AssessmentResults",
|
|
40
|
+
"AssessmentSettings",
|
|
41
|
+
"StandardAssessment",
|
|
42
|
+
"assessments",
|
|
43
|
+
"load_results",
|
|
44
|
+
"save_results",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
49
|
+
class AssessmentResults:
|
|
50
|
+
"""What an assessment found.
|
|
51
|
+
|
|
52
|
+
Attributes:
|
|
53
|
+
run_id: The run's id; each record's id is ``"<run_id>:<instance id>"``.
|
|
54
|
+
instances: What was found for each instance, in the order assessed.
|
|
55
|
+
aggregates: Each aggregation's summary, keyed by its name.
|
|
56
|
+
provenance: How the results were made, as plain values: the
|
|
57
|
+
assessment's settings, the seed, the model information the
|
|
58
|
+
caller gave, whether a teacher observed or intervened, and how
|
|
59
|
+
many lanes ran.
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
run_id: str
|
|
63
|
+
instances: tuple[InstanceResult, ...]
|
|
64
|
+
aggregates: Mapping[str, Summary]
|
|
65
|
+
provenance: Mapping[str, Any]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Assessment(Protocol):
|
|
69
|
+
"""What every assessment provides: a run over a model, giving results."""
|
|
70
|
+
|
|
71
|
+
async def run(
|
|
72
|
+
self,
|
|
73
|
+
model: object,
|
|
74
|
+
*,
|
|
75
|
+
run_id: str,
|
|
76
|
+
seed: int,
|
|
77
|
+
model_info: Mapping[str, Any] | None = None,
|
|
78
|
+
) -> AssessmentResults:
|
|
79
|
+
"""Assess ``model`` and return the results."""
|
|
80
|
+
...
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True)
|
|
84
|
+
class AssessmentSettings:
|
|
85
|
+
"""Settings for the standard assessment."""
|
|
86
|
+
|
|
87
|
+
collections: list[str] = setting(
|
|
88
|
+
min_length=1, description="The collections assessed, served for evaluation."
|
|
89
|
+
)
|
|
90
|
+
measurements: list[str] = setting(
|
|
91
|
+
default_factory=lambda: ["score"],
|
|
92
|
+
min_length=1,
|
|
93
|
+
description="The registered measurements taken of each instance.",
|
|
94
|
+
)
|
|
95
|
+
aggregations: dict[str, AggregationSettings] = setting(
|
|
96
|
+
default_factory=dict, description="The summaries to compute, keyed by name."
|
|
97
|
+
)
|
|
98
|
+
episode: EpisodeSettings = setting(
|
|
99
|
+
default_factory=EpisodeSettings,
|
|
100
|
+
description=(
|
|
101
|
+
"How each instance is attempted: timing, max_steps (a limit per instance), "
|
|
102
|
+
"whether a teacher intervenes, threads."
|
|
103
|
+
),
|
|
104
|
+
)
|
|
105
|
+
max_instances: int | None = setting(
|
|
106
|
+
None, ge=1, description="Assess at most this many instances, in collection order."
|
|
107
|
+
)
|
|
108
|
+
learning_operation: str | None = setting(
|
|
109
|
+
None,
|
|
110
|
+
min_length=1,
|
|
111
|
+
description=(
|
|
112
|
+
"For learning during evaluation: the learning operation called with each "
|
|
113
|
+
"instance's record. None: the model does not learn."
|
|
114
|
+
),
|
|
115
|
+
)
|
|
116
|
+
stop_on_failure: bool = setting(
|
|
117
|
+
False, description="Stop when a measurement raises, instead of recording it as failed."
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
def validate(self) -> None:
|
|
121
|
+
unmeasured = [
|
|
122
|
+
f"{name!r} ({aggregation.measurement!r})"
|
|
123
|
+
for name, aggregation in self.aggregations.items()
|
|
124
|
+
if aggregation.measurement not in self.measurements
|
|
125
|
+
]
|
|
126
|
+
if unmeasured:
|
|
127
|
+
raise ValueError(
|
|
128
|
+
f"aggregations {', '.join(unmeasured)} name measurements that are not taken; "
|
|
129
|
+
f"add them to measurements: {self.measurements}"
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class StandardAssessment:
|
|
134
|
+
"""Runs a model over collections, measures each instance, and aggregates, as set.
|
|
135
|
+
|
|
136
|
+
Each instance is attempted with ``run_episode`` when there is an
|
|
137
|
+
environment, and with ``solve`` (static solving) when there is none.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
config: The settings.
|
|
141
|
+
collections: Where the collections are; each is requested with
|
|
142
|
+
``purpose="evaluation"``, so held-out collections are served.
|
|
143
|
+
task: The task, for the measurements, such as ``"score"``.
|
|
144
|
+
env: Optional. The environment, or a list of environments: one per
|
|
145
|
+
lane, run at once. Without one, instances are solved statically.
|
|
146
|
+
The assessment never closes them.
|
|
147
|
+
teacher: Optional. A teacher the episode loop consults. It observes
|
|
148
|
+
unless ``episode.intervene`` is set.
|
|
149
|
+
teacher_context: Optional. As for ``run_episode``.
|
|
150
|
+
outcome: Optional. Turns a record into what the task scores. By
|
|
151
|
+
default: the last prediction (static) or the final observation
|
|
152
|
+
(with an environment), of the one participant, or keyed by
|
|
153
|
+
agent when there are several.
|
|
154
|
+
store: Optional. Where the records are written.
|
|
155
|
+
|
|
156
|
+
Raises:
|
|
157
|
+
ConfigError: Invalid settings.
|
|
158
|
+
UnknownComponentError: A measurement or aggregator that is not
|
|
159
|
+
registered.
|
|
160
|
+
"""
|
|
161
|
+
|
|
162
|
+
Settings = AssessmentSettings
|
|
163
|
+
|
|
164
|
+
def __init__(
|
|
165
|
+
self,
|
|
166
|
+
config: AssessmentSettings | Mapping[str, Any],
|
|
167
|
+
*,
|
|
168
|
+
collections: Collections,
|
|
169
|
+
task: object,
|
|
170
|
+
env: object = None,
|
|
171
|
+
teacher: object = None,
|
|
172
|
+
teacher_context: TeacherContext | None = None,
|
|
173
|
+
outcome: Callable[[Record], Any] | None = None,
|
|
174
|
+
store: Store | None = None,
|
|
175
|
+
) -> None:
|
|
176
|
+
self.config = validate_settings(AssessmentSettings, config)
|
|
177
|
+
self.measures = {name: measurements.get(name) for name in self.config.measurements}
|
|
178
|
+
for aggregation in self.config.aggregations.values():
|
|
179
|
+
aggregators.get(aggregation.aggregator)
|
|
180
|
+
self.collections, self.task, self.store = collections, task, store
|
|
181
|
+
self.envs = [] if env is None else list(env) if isinstance(env, Sequence) else [env]
|
|
182
|
+
self.teacher, self.teacher_context = teacher, teacher_context
|
|
183
|
+
self.outcome = outcome or _last_outcome
|
|
184
|
+
|
|
185
|
+
async def run(
|
|
186
|
+
self,
|
|
187
|
+
model: object,
|
|
188
|
+
*,
|
|
189
|
+
run_id: str,
|
|
190
|
+
seed: int,
|
|
191
|
+
model_info: Mapping[str, Any] | None = None,
|
|
192
|
+
) -> AssessmentResults:
|
|
193
|
+
"""Assess ``model`` over the collections and return the results.
|
|
194
|
+
|
|
195
|
+
The model is told it is being evaluated (``set_evaluating(True)``,
|
|
196
|
+
then ``False`` at the end), and no learning operation is called
|
|
197
|
+
unless ``learning_operation`` is set.
|
|
198
|
+
|
|
199
|
+
Args:
|
|
200
|
+
model: The model, or a mapping from agent id to model, as for
|
|
201
|
+
``run_episode``.
|
|
202
|
+
run_id: Identifies this run; each record's id is
|
|
203
|
+
``"<run_id>:<instance id>"``.
|
|
204
|
+
seed: Each instance's reset seed is derived from it and the
|
|
205
|
+
instance's id, so it does not depend on the order or the
|
|
206
|
+
lanes. It is passed only to an environment with seeded reset.
|
|
207
|
+
model_info: Optional. Plain values about the model, kept in the
|
|
208
|
+
results, such as ``{"checkpoint": "ckpt-12",
|
|
209
|
+
"episodes_trained": 41200}``.
|
|
210
|
+
|
|
211
|
+
Raises:
|
|
212
|
+
UnknownCollectionError: A collection that does not exist.
|
|
213
|
+
Exception: A model's or environment's own error, as itself;
|
|
214
|
+
the failed record is kept.
|
|
215
|
+
"""
|
|
216
|
+
check_identifier(run_id, "a run id")
|
|
217
|
+
check_int(seed, "seed")
|
|
218
|
+
info = keyed(model_info or {}, "model_info", "names")
|
|
219
|
+
models = list({id(each): each for each in _models(model)}.values())
|
|
220
|
+
operation = self.config.learning_operation
|
|
221
|
+
if operation is not None:
|
|
222
|
+
for each in models:
|
|
223
|
+
if not model_supports(each, operation):
|
|
224
|
+
raise ValueError(f"{name_of(each)} does not support {operation!r}")
|
|
225
|
+
drawn = [
|
|
226
|
+
(name, item)
|
|
227
|
+
for name in self.config.collections
|
|
228
|
+
for item in self.collections.get(name, purpose="evaluation")
|
|
229
|
+
][: self.config.max_instances]
|
|
230
|
+
|
|
231
|
+
await _set_evaluating(models, True)
|
|
232
|
+
try:
|
|
233
|
+
instances = await self._attempt_all(model, models, drawn, run_id, seed)
|
|
234
|
+
finally:
|
|
235
|
+
await _set_evaluating(models, False)
|
|
236
|
+
intervene = self.config.episode.intervene
|
|
237
|
+
teacher = None if self.teacher is None else "intervene" if intervene else "observe"
|
|
238
|
+
return AssessmentResults(
|
|
239
|
+
run_id=run_id,
|
|
240
|
+
instances=tuple(instances),
|
|
241
|
+
aggregates=aggregate(instances, self.config.aggregations),
|
|
242
|
+
provenance={
|
|
243
|
+
"settings": settings_to_dict(self.config),
|
|
244
|
+
"seed": seed,
|
|
245
|
+
"model": info,
|
|
246
|
+
"teacher": teacher,
|
|
247
|
+
"lanes": max(len(self.envs), 1),
|
|
248
|
+
},
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
async def _attempt_all(
|
|
252
|
+
self,
|
|
253
|
+
model: object,
|
|
254
|
+
models: list[object],
|
|
255
|
+
drawn: list[tuple[str, Drawn]],
|
|
256
|
+
run_id: str,
|
|
257
|
+
seed: int,
|
|
258
|
+
) -> list[InstanceResult]:
|
|
259
|
+
"""Attempt every instance, in as many lanes as there are environments."""
|
|
260
|
+
results: dict[int, InstanceResult] = {}
|
|
261
|
+
pending = iter(enumerate(drawn)) # shared by the lanes: each takes the next instance
|
|
262
|
+
lanes = self.envs or [None]
|
|
263
|
+
|
|
264
|
+
async def lane(env: object, key: int | None) -> None:
|
|
265
|
+
for position, (collection, item) in pending:
|
|
266
|
+
results[position] = await self._attempt(
|
|
267
|
+
model, models, env, key, collection, item, run_id, seed
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
many = len(lanes) > 1
|
|
271
|
+
tasks = [
|
|
272
|
+
asyncio.ensure_future(lane(env, i if many else None)) for i, env in enumerate(lanes)
|
|
273
|
+
]
|
|
274
|
+
try:
|
|
275
|
+
await asyncio.gather(*tasks)
|
|
276
|
+
except BaseException:
|
|
277
|
+
for task in tasks:
|
|
278
|
+
task.cancel()
|
|
279
|
+
raise
|
|
280
|
+
return [results[position] for position in range(len(drawn))]
|
|
281
|
+
|
|
282
|
+
async def _attempt(
|
|
283
|
+
self,
|
|
284
|
+
model: object,
|
|
285
|
+
models: list[object],
|
|
286
|
+
env: object,
|
|
287
|
+
lane: int | None,
|
|
288
|
+
collection: str,
|
|
289
|
+
drawn: Drawn,
|
|
290
|
+
run_id: str,
|
|
291
|
+
seed: int,
|
|
292
|
+
) -> InstanceResult:
|
|
293
|
+
"""Attempt one instance, measure it, and let the model learn from it if set."""
|
|
294
|
+
instance, record_id = drawn.instance, f"{run_id}:{drawn.instance.id}"
|
|
295
|
+
if env is None:
|
|
296
|
+
record = await solve(
|
|
297
|
+
model,
|
|
298
|
+
instance,
|
|
299
|
+
record_id=record_id,
|
|
300
|
+
lane=lane,
|
|
301
|
+
provenance=drawn.provenance,
|
|
302
|
+
store=self.store,
|
|
303
|
+
settings=self.config.episode,
|
|
304
|
+
)
|
|
305
|
+
else:
|
|
306
|
+
seeded = environment_supports(env, "seeded_reset")
|
|
307
|
+
record = await run_episode(
|
|
308
|
+
env,
|
|
309
|
+
model,
|
|
310
|
+
instance,
|
|
311
|
+
record_id=record_id,
|
|
312
|
+
seed=_instance_seed(seed, instance.id) if seeded else None,
|
|
313
|
+
teacher=self.teacher,
|
|
314
|
+
teacher_context=self.teacher_context,
|
|
315
|
+
lane=lane,
|
|
316
|
+
provenance=drawn.provenance,
|
|
317
|
+
store=self.store,
|
|
318
|
+
settings=self.config.episode,
|
|
319
|
+
)
|
|
320
|
+
assert record.summary is not None
|
|
321
|
+
if record.summary.status == "failed": # nothing reliable to measure
|
|
322
|
+
failed = MeasuredValue.failed(f"the attempt failed: {record.summary.detail}")
|
|
323
|
+
values = dict.fromkeys(self.measures, failed)
|
|
324
|
+
else:
|
|
325
|
+
trial = Trial(instance, record, self.outcome(record), self.task)
|
|
326
|
+
values = {
|
|
327
|
+
name: self._measure(measure, trial) for name, measure in self.measures.items()
|
|
328
|
+
}
|
|
329
|
+
if self.config.learning_operation is not None:
|
|
330
|
+
for each in models:
|
|
331
|
+
learn = each.learn # type: ignore[attr-defined]
|
|
332
|
+
await Execution().call(learn, self.config.learning_operation, record=record)
|
|
333
|
+
return InstanceResult(
|
|
334
|
+
instance_id=instance.id,
|
|
335
|
+
collection=collection,
|
|
336
|
+
descriptors=instance.descriptors,
|
|
337
|
+
record_id=record_id,
|
|
338
|
+
status=record.summary.status,
|
|
339
|
+
values=values,
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
def _measure(self, measure: Callable[[Trial], Any], trial: Trial) -> MeasuredValue:
|
|
343
|
+
try:
|
|
344
|
+
return MeasuredValue.of(measure(trial))
|
|
345
|
+
except Exception as error:
|
|
346
|
+
if self.config.stop_on_failure:
|
|
347
|
+
raise
|
|
348
|
+
return MeasuredValue.failed(f"{type(error).__name__}: {error}")
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
assessments: Registry[Callable[..., Assessment]] = Registry("assessment")
|
|
352
|
+
"""Registered assessments. Also available as ``ssapling.registries.assessments``.
|
|
353
|
+
|
|
354
|
+
``"standard"`` is built in.
|
|
355
|
+
"""
|
|
356
|
+
assessments.register("standard", StandardAssessment)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
# Saving and loading results
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def save_results(store: Store, results: AssessmentResults) -> None:
|
|
363
|
+
"""Save ``results`` in ``store``, as the document ``"results/<run id>"``."""
|
|
364
|
+
store.save_document(f"results/{results.run_id}", dataclasses.asdict(results))
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def load_results(store: Store, run_id: str) -> AssessmentResults:
|
|
368
|
+
"""The results saved by ``save_results`` for ``run_id``.
|
|
369
|
+
|
|
370
|
+
Raises:
|
|
371
|
+
UnknownDocumentError: The store holds no results for ``run_id``.
|
|
372
|
+
"""
|
|
373
|
+
document = store.load_document(f"results/{run_id}")
|
|
374
|
+
instances = tuple(
|
|
375
|
+
InstanceResult(
|
|
376
|
+
**{
|
|
377
|
+
**doc,
|
|
378
|
+
"values": {name: MeasuredValue(**value) for name, value in doc["values"].items()},
|
|
379
|
+
}
|
|
380
|
+
)
|
|
381
|
+
for doc in document["instances"]
|
|
382
|
+
)
|
|
383
|
+
return AssessmentResults(
|
|
384
|
+
run_id=document["run_id"],
|
|
385
|
+
instances=instances,
|
|
386
|
+
aggregates={name: _summary(doc) for name, doc in document["aggregates"].items()},
|
|
387
|
+
provenance=document["provenance"],
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
# Helpers
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _last_outcome(record: Record) -> Any:
|
|
395
|
+
"""What the task scores by default: the last prediction, or the final observation."""
|
|
396
|
+
if not record.steps:
|
|
397
|
+
return None
|
|
398
|
+
last = record.steps[-1]
|
|
399
|
+
if record.header.static:
|
|
400
|
+
values = last.predictions or {}
|
|
401
|
+
else:
|
|
402
|
+
values = last.transition.observations if last.transition is not None else {}
|
|
403
|
+
participants = record.header.participants
|
|
404
|
+
return values.get(participants[0]) if len(participants) == 1 else dict(values)
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _instance_seed(seed: int, instance_id: str) -> int:
|
|
408
|
+
"""A reset seed for one instance, from the run's seed and the instance's id alone."""
|
|
409
|
+
return random.Random(f"{seed}:{instance_id}").getrandbits(32)
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _models(model: object) -> list[object]:
|
|
413
|
+
return list(model.values()) if isinstance(model, Mapping) else [model]
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
async def _set_evaluating(models: list[object], evaluating: bool) -> None:
|
|
417
|
+
for each in models:
|
|
418
|
+
method = getattr(each, "set_evaluating", None)
|
|
419
|
+
if callable(method):
|
|
420
|
+
await Execution().call(method, evaluating)
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def _summary(doc: Mapping[str, Any]) -> Summary:
|
|
424
|
+
return Summary(
|
|
425
|
+
value=doc["value"],
|
|
426
|
+
contributed=doc["contributed"],
|
|
427
|
+
excluded=doc["excluded"],
|
|
428
|
+
groups={key: _summary(group) for key, group in doc["groups"].items()},
|
|
429
|
+
)
|