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,21 @@
|
|
|
1
|
+
"""Errors specific to interaction."""
|
|
2
|
+
|
|
3
|
+
from ..core.errors import SSAPlingError
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ComponentProcessError(SSAPlingError, RuntimeError):
|
|
7
|
+
"""The process hosting a component cannot do what was asked of it.
|
|
8
|
+
|
|
9
|
+
Raised when the process has exited (it crashed, or the ``in_process``
|
|
10
|
+
block has ended), or when a result could not be sent back from it. An
|
|
11
|
+
error the component raises itself is not wrapped: it arrives as itself.
|
|
12
|
+
|
|
13
|
+
Attributes:
|
|
14
|
+
component: The component's class name.
|
|
15
|
+
problem: What went wrong.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
def __init__(self, component: str, problem: str) -> None:
|
|
19
|
+
self.component = component
|
|
20
|
+
self.problem = problem
|
|
21
|
+
super().__init__(f"The process hosting {component} {problem}.")
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""Running a component in its own process, behind a stand-in that behaves like it.
|
|
2
|
+
|
|
3
|
+
A component normally runs in the caller's process: directly in the event
|
|
4
|
+
loop's thread, or in a worker thread (the runners' ``placement``). A
|
|
5
|
+
component that needs a process of its own, for example because it is
|
|
6
|
+
CPU-bound, needs its own GPU context, or might crash, is built in a
|
|
7
|
+
long-lived worker process by ``in_process``, which returns a **stand-in**.
|
|
8
|
+
|
|
9
|
+
The stand-in has the component's public methods and attributes, so
|
|
10
|
+
everything that uses a component (the runners, ``supports``, the episode
|
|
11
|
+
loop) uses it unchanged. Each is looked up in the worker when it is used:
|
|
12
|
+
|
|
13
|
+
- A method comes back as a stand-in method: ``def`` or ``async def``
|
|
14
|
+
exactly as the component's is, taking the same parameters. A call runs in
|
|
15
|
+
the worker; the caller waits.
|
|
16
|
+
- Any other attribute comes back as its value, so it is never out of date.
|
|
17
|
+
- An error the component raises arrives as itself.
|
|
18
|
+
|
|
19
|
+
The worker is started with ``spawn``, which works on every platform, so the
|
|
20
|
+
factory, its arguments, and every argument and result must be picklable.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
import asyncio
|
|
24
|
+
import inspect
|
|
25
|
+
import pickle
|
|
26
|
+
import threading
|
|
27
|
+
from collections.abc import Callable, Iterator
|
|
28
|
+
from contextlib import contextmanager, suppress
|
|
29
|
+
from typing import Any, cast
|
|
30
|
+
|
|
31
|
+
from .errors import ComponentProcessError
|
|
32
|
+
|
|
33
|
+
__all__ = ["in_process"]
|
|
34
|
+
|
|
35
|
+
_STOP_TIMEOUT = 5.0
|
|
36
|
+
"""Seconds to wait for a call in progress before stopping a worker forcibly."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@contextmanager
|
|
40
|
+
def in_process[T](factory: Callable[..., T], /, *args: Any, **kwargs: Any) -> Iterator[T]:
|
|
41
|
+
"""Build a component in a worker process, and stand in for it until the block ends.
|
|
42
|
+
|
|
43
|
+
Example::
|
|
44
|
+
|
|
45
|
+
with in_process(DigitPadEnv) as env:
|
|
46
|
+
first = await runner.reset(env, options=instance.inputs)
|
|
47
|
+
|
|
48
|
+
with in_process(build_model, "checkpoints/7") as model:
|
|
49
|
+
...
|
|
50
|
+
|
|
51
|
+
The worker builds the component with ``factory(*args, **kwargs)`` and
|
|
52
|
+
keeps it until the block ends. A factory that needs the worker prepared
|
|
53
|
+
first, for example by the project's ``register_components``, is a
|
|
54
|
+
module-level function that does so before building. Then it
|
|
55
|
+
stops, once any call in progress has finished, or after 5 seconds by
|
|
56
|
+
force. Calling the component's own ``close``, if it has one, is up to
|
|
57
|
+
its owner, before the block ends.
|
|
58
|
+
|
|
59
|
+
A synchronous method of the stand-in blocks the thread that calls it
|
|
60
|
+
until the worker answers. To keep an event loop running meanwhile, and to
|
|
61
|
+
allow a timeout, run the component in a thread as well
|
|
62
|
+
(``placement="thread"``), as for any synchronous component.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
factory: Builds the component: a class, or a function defined at
|
|
66
|
+
module level.
|
|
67
|
+
*args, **kwargs: Passed to ``factory``.
|
|
68
|
+
|
|
69
|
+
Yields:
|
|
70
|
+
The stand-in.
|
|
71
|
+
|
|
72
|
+
Raises:
|
|
73
|
+
Exception: Whatever ``factory`` raises, as itself, when the block is
|
|
74
|
+
entered.
|
|
75
|
+
ComponentProcessError: From a later call: the worker has exited, or
|
|
76
|
+
a result could not be sent back.
|
|
77
|
+
"""
|
|
78
|
+
host = _Host(factory, args, kwargs)
|
|
79
|
+
try:
|
|
80
|
+
yield cast(T, host.stand_in)
|
|
81
|
+
finally:
|
|
82
|
+
host.stop()
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class _Host:
|
|
86
|
+
"""The caller's side: the worker process, and the pipe to it."""
|
|
87
|
+
|
|
88
|
+
def __init__(
|
|
89
|
+
self, factory: Callable[..., Any], args: tuple[Any, ...], kwargs: dict[str, Any]
|
|
90
|
+
) -> None:
|
|
91
|
+
# Imported here: importing ssapling must not load multiprocessing.
|
|
92
|
+
import multiprocessing
|
|
93
|
+
|
|
94
|
+
context = multiprocessing.get_context("spawn")
|
|
95
|
+
self._connection, child = context.Pipe()
|
|
96
|
+
self._process = context.Process(
|
|
97
|
+
target=_serve, args=(child, factory, args, kwargs), daemon=True
|
|
98
|
+
)
|
|
99
|
+
self._lock = threading.Lock() # one request at a time, from any thread
|
|
100
|
+
self._stopped = False
|
|
101
|
+
self.name = getattr(factory, "__qualname__", repr(factory))
|
|
102
|
+
try:
|
|
103
|
+
self._process.start()
|
|
104
|
+
finally:
|
|
105
|
+
child.close()
|
|
106
|
+
status, value = self._receive()
|
|
107
|
+
if status == "error":
|
|
108
|
+
self.stop()
|
|
109
|
+
value.add_note(f"While building {self.name} in a worker process.")
|
|
110
|
+
raise value
|
|
111
|
+
self.name = value # the component's class name
|
|
112
|
+
self.stand_in: _StandIn = object.__new__(type(self.name, (_StandIn,), {}))
|
|
113
|
+
object.__setattr__(self.stand_in, "_host", self)
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def pid(self) -> int | None:
|
|
117
|
+
return self._process.pid
|
|
118
|
+
|
|
119
|
+
def request(
|
|
120
|
+
self,
|
|
121
|
+
kind: str,
|
|
122
|
+
name: str,
|
|
123
|
+
args: tuple[Any, ...] = (),
|
|
124
|
+
kwargs: dict[str, Any] | None = None,
|
|
125
|
+
) -> Any:
|
|
126
|
+
"""Call a method of the component (``"call"``) or read an attribute (``"get"``)."""
|
|
127
|
+
with self._lock:
|
|
128
|
+
if self._stopped:
|
|
129
|
+
raise ComponentProcessError(self.name, "has stopped: its in_process block ended")
|
|
130
|
+
try:
|
|
131
|
+
self._connection.send((kind, name, args, kwargs or {}))
|
|
132
|
+
except OSError:
|
|
133
|
+
raise self._exited() from None
|
|
134
|
+
except Exception as error:
|
|
135
|
+
error.add_note(f"{self.name} runs in another process, so arguments are pickled.")
|
|
136
|
+
raise
|
|
137
|
+
status, value = self._receive()
|
|
138
|
+
if status == "error":
|
|
139
|
+
value.add_note(f"Raised by {self.name}.{name} in its worker process.")
|
|
140
|
+
raise value
|
|
141
|
+
if status == "method":
|
|
142
|
+
return _method(self, name, *value)
|
|
143
|
+
return value
|
|
144
|
+
|
|
145
|
+
def stop(self) -> None:
|
|
146
|
+
"""Stop the worker once any call in progress has finished, or by force after a while."""
|
|
147
|
+
self._stopped = True
|
|
148
|
+
with suppress(OSError): # it may have exited already
|
|
149
|
+
self._connection.send(None) # read once the call in progress, if any, is answered
|
|
150
|
+
self._process.join(_STOP_TIMEOUT)
|
|
151
|
+
if self._process.is_alive():
|
|
152
|
+
self._process.terminate()
|
|
153
|
+
self._process.join()
|
|
154
|
+
self._connection.close()
|
|
155
|
+
|
|
156
|
+
def _receive(self) -> tuple[str, Any]:
|
|
157
|
+
try:
|
|
158
|
+
status, value = self._connection.recv()
|
|
159
|
+
except (EOFError, OSError):
|
|
160
|
+
raise self._exited() from None
|
|
161
|
+
except Exception as error: # the reply arrived but cannot be rebuilt here
|
|
162
|
+
problem = f"sent back something this process cannot rebuild ({_describe(error)})"
|
|
163
|
+
raise ComponentProcessError(self.name, problem) from None
|
|
164
|
+
if status == "unsent":
|
|
165
|
+
raise ComponentProcessError(self.name, f"could not send back {value}")
|
|
166
|
+
return status, value
|
|
167
|
+
|
|
168
|
+
def _exited(self) -> ComponentProcessError:
|
|
169
|
+
self._process.join(timeout=1)
|
|
170
|
+
return ComponentProcessError(self.name, f"exited (exit code {self._process.exitcode})")
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class _StandIn:
|
|
174
|
+
"""Stands in for a component in another process; see ``in_process``.
|
|
175
|
+
|
|
176
|
+
Each hosted component gets a subclass named after its class, so messages
|
|
177
|
+
name the component.
|
|
178
|
+
"""
|
|
179
|
+
|
|
180
|
+
_host: _Host
|
|
181
|
+
|
|
182
|
+
def __getattr__(self, name: str) -> Any:
|
|
183
|
+
# Every public attribute is looked up in the worker.
|
|
184
|
+
if name.startswith("_"):
|
|
185
|
+
raise AttributeError(name)
|
|
186
|
+
return self._host.request("get", name)
|
|
187
|
+
|
|
188
|
+
def __setattr__(self, name: str, value: Any) -> None:
|
|
189
|
+
raise AttributeError(
|
|
190
|
+
f"cannot set {name!r}: {type(self).__name__} runs in another process, so change it "
|
|
191
|
+
"through one of its methods"
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
def __repr__(self) -> str:
|
|
195
|
+
return f"<{type(self).__name__} in process {self._host.pid}>"
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _method(
|
|
199
|
+
host: _Host, name: str, is_async: bool, signature: inspect.Signature | None
|
|
200
|
+
) -> Callable[..., Any]:
|
|
201
|
+
"""A stand-in for one method: ``def`` or ``async def`` as the original, with its parameters."""
|
|
202
|
+
|
|
203
|
+
def call(*args: Any, **kwargs: Any) -> Any:
|
|
204
|
+
return host.request("call", name, args, kwargs)
|
|
205
|
+
|
|
206
|
+
async def call_async(*args: Any, **kwargs: Any) -> Any:
|
|
207
|
+
# The request blocks, so it waits in a thread while the event loop goes on.
|
|
208
|
+
return await asyncio.to_thread(host.request, "call", name, args, kwargs)
|
|
209
|
+
|
|
210
|
+
method: Callable[..., Any] = call_async if is_async else call
|
|
211
|
+
method.__name__, method.__qualname__ = name, f"{host.name}.{name}"
|
|
212
|
+
if signature is not None:
|
|
213
|
+
method.__signature__ = signature # type: ignore[attr-defined]
|
|
214
|
+
return method
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
# In the worker process
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _serve(
|
|
221
|
+
connection: Any, factory: Callable[..., Any], args: tuple[Any, ...], kwargs: dict[str, Any]
|
|
222
|
+
) -> None:
|
|
223
|
+
"""Build the component, then answer requests until told to stop."""
|
|
224
|
+
try:
|
|
225
|
+
component = factory(*args, **kwargs)
|
|
226
|
+
reply: tuple[str, Any] = ("ok", type(component).__name__)
|
|
227
|
+
except Exception as error:
|
|
228
|
+
reply = ("error", error)
|
|
229
|
+
_send(connection, reply)
|
|
230
|
+
if reply[0] != "ok":
|
|
231
|
+
return
|
|
232
|
+
|
|
233
|
+
loop: asyncio.AbstractEventLoop | None = None # for async methods, made when first needed
|
|
234
|
+
while True:
|
|
235
|
+
try:
|
|
236
|
+
request = connection.recv()
|
|
237
|
+
except EOFError:
|
|
238
|
+
break
|
|
239
|
+
if request is None:
|
|
240
|
+
break
|
|
241
|
+
kind, name, args, kwargs = request
|
|
242
|
+
try:
|
|
243
|
+
value = getattr(component, name)
|
|
244
|
+
if kind == "call":
|
|
245
|
+
value = value(*args, **kwargs)
|
|
246
|
+
if inspect.isawaitable(value):
|
|
247
|
+
loop = loop or asyncio.new_event_loop()
|
|
248
|
+
value = loop.run_until_complete(value)
|
|
249
|
+
reply = ("ok", value)
|
|
250
|
+
elif callable(value) and not isinstance(value, type): # a method: describe it
|
|
251
|
+
reply = ("method", (inspect.iscoroutinefunction(value), _signature(value)))
|
|
252
|
+
else:
|
|
253
|
+
reply = ("ok", value)
|
|
254
|
+
except (Exception, asyncio.CancelledError) as error:
|
|
255
|
+
reply = ("error", error)
|
|
256
|
+
_send(connection, reply)
|
|
257
|
+
if loop is not None:
|
|
258
|
+
loop.close()
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _signature(method: Callable[..., Any]) -> inspect.Signature | None:
|
|
262
|
+
"""``method``'s signature without annotations and default values, which may not pickle."""
|
|
263
|
+
try:
|
|
264
|
+
signature = inspect.signature(method)
|
|
265
|
+
except (TypeError, ValueError):
|
|
266
|
+
return None # the stand-in then takes any arguments
|
|
267
|
+
parameters = [
|
|
268
|
+
p.replace(annotation=p.empty, default=p.empty if p.default is p.empty else ...)
|
|
269
|
+
for p in signature.parameters.values()
|
|
270
|
+
]
|
|
271
|
+
return signature.replace(parameters=parameters, return_annotation=signature.empty)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def _send(connection: Any, reply: tuple[str, Any]) -> None:
|
|
275
|
+
"""Send ``reply``, or, if it cannot be sent and rebuilt, say so in words."""
|
|
276
|
+
status, value = reply
|
|
277
|
+
try:
|
|
278
|
+
if status == "error":
|
|
279
|
+
pickle.loads(pickle.dumps(value)) # an error that cannot be rebuilt is sent as text
|
|
280
|
+
connection.send(reply)
|
|
281
|
+
except Exception as problem:
|
|
282
|
+
what = f"its error {_describe(value)}" if status == "error" else f"a {type(value).__name__}"
|
|
283
|
+
connection.send(("unsent", f"{what} ({_describe(problem)})"))
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _describe(error: BaseException) -> str:
|
|
287
|
+
return f"{type(error).__name__}: {error}"
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""SSAPling models.
|
|
2
|
+
|
|
3
|
+
Responsibility: Interfaces and lifecycle for user-defined models, their inputs
|
|
4
|
+
and outputs, and internal state.
|
|
5
|
+
|
|
6
|
+
Not its responsibility: Where data comes from or when learning happens.
|
|
7
|
+
|
|
8
|
+
May import: core. Enforced by tests/test_layering.py.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
|
|
13
|
+
from ..core import Registry
|
|
14
|
+
from .buffering import as_buffered
|
|
15
|
+
from .contracts import (
|
|
16
|
+
ActModel,
|
|
17
|
+
BufferedModel,
|
|
18
|
+
Model,
|
|
19
|
+
check_descriptions,
|
|
20
|
+
filter_signals,
|
|
21
|
+
supports,
|
|
22
|
+
)
|
|
23
|
+
from .errors import DescriptionMismatchError
|
|
24
|
+
from .types import NOTHING, DescriptionKind, DescriptionMismatch, Nothing, Refusal
|
|
25
|
+
|
|
26
|
+
registry: Registry[Callable[..., Model]] = Registry("model")
|
|
27
|
+
"""Registered models. Also available as ``ssapling.registries.models``."""
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"NOTHING",
|
|
31
|
+
"ActModel",
|
|
32
|
+
"BufferedModel",
|
|
33
|
+
"DescriptionKind",
|
|
34
|
+
"DescriptionMismatch",
|
|
35
|
+
"DescriptionMismatchError",
|
|
36
|
+
"Model",
|
|
37
|
+
"Nothing",
|
|
38
|
+
"Refusal",
|
|
39
|
+
"as_buffered",
|
|
40
|
+
"check_descriptions",
|
|
41
|
+
"filter_signals",
|
|
42
|
+
"registry",
|
|
43
|
+
"supports",
|
|
44
|
+
]
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"""Giving an act-only model the buffered interface, so simple models never deal with buffers."""
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
from collections import deque
|
|
5
|
+
from collections.abc import Awaitable, Callable, Hashable, Mapping
|
|
6
|
+
from typing import Any, cast
|
|
7
|
+
|
|
8
|
+
from ..core._declarations import name_of, takes
|
|
9
|
+
from .contracts import BufferedModel, Model
|
|
10
|
+
from .types import NOTHING
|
|
11
|
+
|
|
12
|
+
__all__ = ["as_buffered"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def as_buffered(model: Model) -> BufferedModel:
|
|
16
|
+
"""``model`` with the buffered interface: ``perceive``, ``poll``, and ``advance``.
|
|
17
|
+
|
|
18
|
+
A model that already has ``perceive`` and ``poll`` is returned unchanged.
|
|
19
|
+
An act-only model is wrapped:
|
|
20
|
+
|
|
21
|
+
- ``perceive(observations)`` queues the observations.
|
|
22
|
+
- ``advance()`` calls the model's ``act`` on the oldest queued
|
|
23
|
+
observations and queues the output. So an act-only model needs exactly
|
|
24
|
+
one internal step per output.
|
|
25
|
+
- ``poll()`` returns the oldest output not yet read, or ``NOTHING``.
|
|
26
|
+
- ``act(observations)`` still calls the model's ``act`` directly.
|
|
27
|
+
|
|
28
|
+
The queues keep every observation and output, in order, so nothing is
|
|
29
|
+
dropped silently: what to do with an output that arrives late is the
|
|
30
|
+
coordinating code's choice. ``advance`` and ``act`` are ``async def``
|
|
31
|
+
exactly when the model's ``act`` is. Each method takes an optional
|
|
32
|
+
``key``, so one model can serve several participants or lanes, each with
|
|
33
|
+
its own queues (see ``reset_episode``).
|
|
34
|
+
|
|
35
|
+
``export_state()`` gives the model's own state, if it has one, with the
|
|
36
|
+
queues, so a checkpoint taken mid-step keeps the step, and
|
|
37
|
+
``restore_state(state)`` returns to it. Everything else, such as
|
|
38
|
+
``learn`` or ``learning_operations``, is the model's own, reached
|
|
39
|
+
through the wrapper.
|
|
40
|
+
|
|
41
|
+
Raises:
|
|
42
|
+
TypeError: ``model`` has neither ``act`` nor both ``perceive`` and
|
|
43
|
+
``poll``.
|
|
44
|
+
"""
|
|
45
|
+
perceive, poll = getattr(model, "perceive", None), getattr(model, "poll", None)
|
|
46
|
+
if callable(perceive) and callable(poll):
|
|
47
|
+
return cast(BufferedModel, model)
|
|
48
|
+
if callable(perceive) or callable(poll):
|
|
49
|
+
missing = "poll" if callable(perceive) else "perceive"
|
|
50
|
+
raise TypeError(f"{name_of(model)} has a buffered interface without {missing}")
|
|
51
|
+
act = getattr(model, "act", None)
|
|
52
|
+
if not callable(act):
|
|
53
|
+
raise TypeError(
|
|
54
|
+
f"{name_of(model)} is not a model: it has no act method, and no perceive and poll"
|
|
55
|
+
)
|
|
56
|
+
if inspect.iscoroutinefunction(act):
|
|
57
|
+
return _AsyncActAdapter(model)
|
|
58
|
+
return _ActAdapter(model)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class _Buffers:
|
|
62
|
+
"""The parts of the adapter that do not depend on whether ``act`` is async."""
|
|
63
|
+
|
|
64
|
+
def __init__(self, model: object) -> None:
|
|
65
|
+
self.model = model
|
|
66
|
+
self._act: Callable[..., Any] = model.act # type: ignore[attr-defined]
|
|
67
|
+
self._inputs: dict[Hashable | None, deque[Any]] = {}
|
|
68
|
+
self._outputs: dict[Hashable | None, deque[Any]] = {}
|
|
69
|
+
|
|
70
|
+
def perceive(self, observations: Any, *, key: Hashable | None = None) -> None:
|
|
71
|
+
"""Queue ``observations`` for the model."""
|
|
72
|
+
_check_key(self._act, key, self.model)
|
|
73
|
+
self._inputs.setdefault(key, deque()).append(observations)
|
|
74
|
+
|
|
75
|
+
def poll(self, *, key: Hashable | None = None) -> Any:
|
|
76
|
+
"""The oldest output not yet read, or ``NOTHING``."""
|
|
77
|
+
outputs = self._outputs.get(key)
|
|
78
|
+
return outputs.popleft() if outputs else NOTHING
|
|
79
|
+
|
|
80
|
+
def reset_episode(self, *, key: Hashable | None = None) -> Any:
|
|
81
|
+
"""Empty the queues for ``key``, then call the model's ``reset_episode``, if it has one.
|
|
82
|
+
|
|
83
|
+
Returns what the model's ``reset_episode`` returns, which callers
|
|
84
|
+
await if the model's method is ``async def``.
|
|
85
|
+
"""
|
|
86
|
+
reset = getattr(self.model, "reset_episode", None)
|
|
87
|
+
if reset is not None:
|
|
88
|
+
_check_key(reset, key, self.model) # before emptying anything
|
|
89
|
+
self._inputs.pop(key, None)
|
|
90
|
+
self._outputs.pop(key, None)
|
|
91
|
+
return None if reset is None else _call(reset, key, self.model)
|
|
92
|
+
|
|
93
|
+
def export_state(self) -> Any:
|
|
94
|
+
"""The model's state (``None`` if it keeps none) and the queues, as
|
|
95
|
+
``{"model": ..., "queues": [[key, observations, outputs], ...]}``.
|
|
96
|
+
|
|
97
|
+
The queues are copies, one entry per key, in order. Awaitable exactly
|
|
98
|
+
when the model's ``export_state`` is ``async def``.
|
|
99
|
+
"""
|
|
100
|
+
queues = [
|
|
101
|
+
[key, list(self._inputs.get(key, ())), list(self._outputs.get(key, ()))]
|
|
102
|
+
for key in dict.fromkeys([*self._inputs, *self._outputs])
|
|
103
|
+
]
|
|
104
|
+
export = getattr(self.model, "export_state", None)
|
|
105
|
+
state = None if export is None else export()
|
|
106
|
+
if inspect.isawaitable(state):
|
|
107
|
+
return _with_queues(state, queues)
|
|
108
|
+
return {"model": state, "queues": queues}
|
|
109
|
+
|
|
110
|
+
def restore_state(self, state: Mapping[str, Any]) -> Any:
|
|
111
|
+
"""Return to an exported state: the queues, then the model's own state.
|
|
112
|
+
|
|
113
|
+
A key that came back as a list, as JSON gives a tuple, is a tuple
|
|
114
|
+
again. Awaitable exactly when the model's ``restore_state`` is
|
|
115
|
+
``async def``.
|
|
116
|
+
"""
|
|
117
|
+
self._inputs = {_key(key): deque(inputs) for key, inputs, _ in state["queues"]}
|
|
118
|
+
self._outputs = {_key(key): deque(outputs) for key, _, outputs in state["queues"]}
|
|
119
|
+
restore = getattr(self.model, "restore_state", None)
|
|
120
|
+
return None if restore is None else restore(state["model"])
|
|
121
|
+
|
|
122
|
+
def _next_input(self, key: Hashable | None) -> tuple[bool, Any]:
|
|
123
|
+
inputs = self._inputs.get(key)
|
|
124
|
+
return (True, inputs.popleft()) if inputs else (False, None)
|
|
125
|
+
|
|
126
|
+
def _put_output(self, key: Hashable | None, output: Any) -> None:
|
|
127
|
+
self._outputs.setdefault(key, deque()).append(output)
|
|
128
|
+
|
|
129
|
+
def __getattr__(self, name: str) -> Any:
|
|
130
|
+
# Called only for attributes the adapter lacks: those are the model's.
|
|
131
|
+
if name == "model" or name.startswith("_"):
|
|
132
|
+
raise AttributeError(name)
|
|
133
|
+
return getattr(self.model, name)
|
|
134
|
+
|
|
135
|
+
def __repr__(self) -> str:
|
|
136
|
+
return f"as_buffered({self.model!r})"
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class _ActAdapter(_Buffers):
|
|
140
|
+
"""An act-only model with a synchronous ``act``, seen through buffers."""
|
|
141
|
+
|
|
142
|
+
def advance(self, *, key: Hashable | None = None) -> None:
|
|
143
|
+
"""Act on the oldest queued observations, if any, and queue the output."""
|
|
144
|
+
waiting, observations = self._next_input(key)
|
|
145
|
+
if waiting:
|
|
146
|
+
self._put_output(key, _call(self._act, key, self.model, observations))
|
|
147
|
+
|
|
148
|
+
def act(self, observations: Any, *, key: Hashable | None = None) -> Any:
|
|
149
|
+
"""The model's own ``act``, called directly."""
|
|
150
|
+
return _call(self._act, key, self.model, observations)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class _AsyncActAdapter(_Buffers):
|
|
154
|
+
"""An act-only model with an ``async def act``, seen through buffers."""
|
|
155
|
+
|
|
156
|
+
async def advance(self, *, key: Hashable | None = None) -> None:
|
|
157
|
+
"""Act on the oldest queued observations, if any, and queue the output."""
|
|
158
|
+
waiting, observations = self._next_input(key)
|
|
159
|
+
if waiting:
|
|
160
|
+
self._put_output(key, await _call(self._act, key, self.model, observations))
|
|
161
|
+
|
|
162
|
+
async def act(self, observations: Any, *, key: Hashable | None = None) -> Any:
|
|
163
|
+
"""The model's own ``act``, called directly."""
|
|
164
|
+
return await _call(self._act, key, self.model, observations)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
async def _with_queues(state: Awaitable[Any], queues: list[Any]) -> dict[str, Any]:
|
|
168
|
+
return {"model": await state, "queues": queues}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _key(key: Any) -> Hashable | None:
|
|
172
|
+
"""A lane key as exported: a list (a tuple, through JSON) becomes a tuple again."""
|
|
173
|
+
return tuple(_key(part) for part in key) if isinstance(key, list) else key
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _call(method: Callable[..., Any], key: Hashable | None, model: object, *args: Any) -> Any:
|
|
177
|
+
"""Call ``method``, passing ``key=`` only when there is one."""
|
|
178
|
+
if key is None:
|
|
179
|
+
return method(*args)
|
|
180
|
+
_check_key(method, key, model)
|
|
181
|
+
return method(*args, key=key)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _check_key(method: Callable[..., Any], key: Hashable | None, model: object) -> None:
|
|
185
|
+
if key is not None and not takes(method, "key"):
|
|
186
|
+
raise TypeError(
|
|
187
|
+
f"{name_of(model)}.{getattr(method, '__name__', 'method')} does not take key=, so it "
|
|
188
|
+
"cannot keep participants or lanes apart; give it a key=None parameter"
|
|
189
|
+
)
|