mimiry-serverless 0.7.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.
- mimiry_serverless/__init__.py +44 -0
- mimiry_serverless/_errors.py +77 -0
- mimiry_serverless/_function.py +264 -0
- mimiry_serverless/_image.py +104 -0
- mimiry_serverless/_results.py +124 -0
- mimiry_serverless/_runtime.py +303 -0
- mimiry_serverless/_session.py +378 -0
- mimiry_serverless-0.7.0.dist-info/METADATA +75 -0
- mimiry_serverless-0.7.0.dist-info/RECORD +12 -0
- mimiry_serverless-0.7.0.dist-info/WHEEL +4 -0
- mimiry_serverless-0.7.0.dist-info/licenses/LICENSE +202 -0
- mimiry_serverless-0.7.0.dist-info/licenses/NOTICE +4 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Run Python functions on Mimiry GPUs.
|
|
2
|
+
|
|
3
|
+
from mimiry_serverless import function, Image
|
|
4
|
+
|
|
5
|
+
@function(gpu="RTX_48G_PCIe", image=Image.python().pip_install("torch"))
|
|
6
|
+
def matmul(n: int) -> float:
|
|
7
|
+
import torch
|
|
8
|
+
a = torch.rand(n, n, device="cuda")
|
|
9
|
+
return float((a @ a).sum())
|
|
10
|
+
|
|
11
|
+
print(matmul.remote(4096))
|
|
12
|
+
|
|
13
|
+
Built on mimiry-sdk: every call goes through the `mimiry` binary, over SSH through the Mimiry
|
|
14
|
+
gateway, with the session's host key checked. The function, its arguments and its result never
|
|
15
|
+
travel in a session request; a result loads only if its types are allowed (see `function`).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from ._errors import (
|
|
19
|
+
MapError,
|
|
20
|
+
RemoteFunctionError,
|
|
21
|
+
ResultParseError,
|
|
22
|
+
ResultTypeRefused,
|
|
23
|
+
SessionError,
|
|
24
|
+
SessionFailed,
|
|
25
|
+
)
|
|
26
|
+
from ._function import Function, RunResult, configure, function, run
|
|
27
|
+
from ._image import Image
|
|
28
|
+
from ._session import RunInfo
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"Function",
|
|
32
|
+
"Image",
|
|
33
|
+
"MapError",
|
|
34
|
+
"RemoteFunctionError",
|
|
35
|
+
"ResultParseError",
|
|
36
|
+
"ResultTypeRefused",
|
|
37
|
+
"RunInfo",
|
|
38
|
+
"RunResult",
|
|
39
|
+
"SessionError",
|
|
40
|
+
"SessionFailed",
|
|
41
|
+
"configure",
|
|
42
|
+
"function",
|
|
43
|
+
"run",
|
|
44
|
+
]
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Errors. Everything here derives from mimiry.MimiryError, the SDK's own base."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from mimiry import MimiryError
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class SessionError(MimiryError):
|
|
11
|
+
"""A function's session could not do its work. `run` is its RunInfo, when one existed."""
|
|
12
|
+
|
|
13
|
+
kind = "serverless"
|
|
14
|
+
|
|
15
|
+
def __init__(self, message: str, *, session_id: str | None = None, run: Any = None):
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
self.session_id = session_id
|
|
18
|
+
self.run = run
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class SessionFailed(SessionError):
|
|
22
|
+
"""The session ended before the call finished: `state` and `stop_reason` say how."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, message: str, *, session_id: str | None = None, state: str | None = None,
|
|
25
|
+
stop_reason: str | None = None, run: Any = None):
|
|
26
|
+
super().__init__(message, session_id=session_id, run=run)
|
|
27
|
+
self.state = state
|
|
28
|
+
self.stop_reason = stop_reason
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class MapError(SessionError):
|
|
32
|
+
"""`.map()` could not complete every item. `results` has every item, with None where one
|
|
33
|
+
failed or was never reached; `failures` is [(index, exception)]."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, message: str, *, results: list, failures: list, total: int, run: Any = None,
|
|
36
|
+
session_id: str | None = None):
|
|
37
|
+
super().__init__(message, session_id=session_id, run=run)
|
|
38
|
+
self.results = results
|
|
39
|
+
self.failures = failures
|
|
40
|
+
self.total = total
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def completed(self) -> int:
|
|
44
|
+
return self.total - len(self.failures)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ResultParseError(MimiryError):
|
|
48
|
+
"""The function ran, but its result could not be read."""
|
|
49
|
+
|
|
50
|
+
kind = "serverless"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class ResultTypeRefused(ResultParseError):
|
|
54
|
+
"""The result names a type that is not on the allow-list, and so was not loaded."""
|
|
55
|
+
|
|
56
|
+
def __init__(self, module: str, name: str):
|
|
57
|
+
self.module, self.name = module, name
|
|
58
|
+
super().__init__(
|
|
59
|
+
f"the result holds {module}.{name}, which is not on the allow-list, so it was not "
|
|
60
|
+
"loaded: loading a result runs the code it names. To allow it: annotate the "
|
|
61
|
+
f"function's return type with it, or add it to result_types=[...], or set "
|
|
62
|
+
"trust_results=True if you trust everything that runs in the container."
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class RemoteFunctionError(MimiryError):
|
|
67
|
+
"""The function raised inside the container. `remote_type` and `remote_traceback` are its own."""
|
|
68
|
+
|
|
69
|
+
kind = "serverless"
|
|
70
|
+
|
|
71
|
+
def __init__(self, message: str, *, remote_type: str, remote_traceback: str):
|
|
72
|
+
super().__init__(message)
|
|
73
|
+
self.remote_type = remote_type
|
|
74
|
+
self.remote_traceback = remote_traceback
|
|
75
|
+
|
|
76
|
+
def __str__(self) -> str:
|
|
77
|
+
return f"{self.remote_type}: {self.args[0]}\n\nRemote traceback:\n{self.remote_traceback}"
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
"""`@function`: run a Python function on a Mimiry GPU.
|
|
2
|
+
|
|
3
|
+
`.remote()` starts a session, runs one call and ends the session. `.map()` starts one session and
|
|
4
|
+
runs every item through it, so the start is paid once. The function and its arguments travel over
|
|
5
|
+
SSH through the Mimiry gateway, never in the session request; the result comes back the same way
|
|
6
|
+
and loads only if its types are on the allow-list (see _results.py).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any, Callable, Iterable
|
|
13
|
+
|
|
14
|
+
import cloudpickle
|
|
15
|
+
from mimiry import Client
|
|
16
|
+
|
|
17
|
+
from ._errors import MapError, RemoteFunctionError, ResultParseError, SessionError
|
|
18
|
+
from ._image import Image, as_image, check_python
|
|
19
|
+
from ._results import allowed_names, types_from_annotation
|
|
20
|
+
from ._session import RunInfo, Session, Spec
|
|
21
|
+
|
|
22
|
+
_defaults: dict[str, str | None] = {"host": None, "key": None}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def configure(*, host: str | None = None, key: str | None = None) -> None:
|
|
26
|
+
"""The host and SSH key every function uses unless it names its own. Unset, they come from
|
|
27
|
+
MIMIRY_HOST / MIMIRY_SSH_KEY, then from what `mimiry auth` saved."""
|
|
28
|
+
_defaults["host"], _defaults["key"] = host, key
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _list(v: str | list[str] | None) -> list[str] | None:
|
|
32
|
+
if v is None:
|
|
33
|
+
return None
|
|
34
|
+
return [v] if isinstance(v, str) else list(v)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class _Config:
|
|
39
|
+
gpu: list[str] | None
|
|
40
|
+
family: list[str] | None
|
|
41
|
+
min_vram: int | None
|
|
42
|
+
gpu_count: int
|
|
43
|
+
image: Image
|
|
44
|
+
timeout: int
|
|
45
|
+
location: str | None
|
|
46
|
+
max_rate: float | None
|
|
47
|
+
env: dict[str, str]
|
|
48
|
+
volumes: dict[str, str]
|
|
49
|
+
name: str | None
|
|
50
|
+
result_types: list[type]
|
|
51
|
+
trust_results: bool
|
|
52
|
+
host: str | None
|
|
53
|
+
key: str | None
|
|
54
|
+
|
|
55
|
+
def client(self) -> Client:
|
|
56
|
+
return Client(host=self.host or _defaults["host"], key=self.key or _defaults["key"])
|
|
57
|
+
|
|
58
|
+
def spec(self, name: str) -> Spec:
|
|
59
|
+
return Spec(image=self.image, gpu=self.gpu, family=self.family, min_vram_gb=self.min_vram,
|
|
60
|
+
gpu_count=self.gpu_count, location=self.location, max_rate=self.max_rate, env=self.env,
|
|
61
|
+
volumes=self.volumes, timeout=self.timeout, name=self.name or name)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Function:
|
|
65
|
+
"""A function bound to the machine it runs on. Made by `@function`."""
|
|
66
|
+
|
|
67
|
+
def __init__(self, fn: Callable, cfg: _Config):
|
|
68
|
+
self._fn = fn
|
|
69
|
+
self._cfg = cfg
|
|
70
|
+
self.__name__ = getattr(fn, "__name__", "function")
|
|
71
|
+
self.__doc__ = fn.__doc__
|
|
72
|
+
#: The session, its GPU and what it cost, for the last .remote() or .map(); None before.
|
|
73
|
+
self.last_run: RunInfo | None = None
|
|
74
|
+
types = set(cfg.result_types) | types_from_annotation(fn)
|
|
75
|
+
self._allowed = None if cfg.trust_results else allowed_names(types)
|
|
76
|
+
# Classes defined in the calling script: the container names them in its __main__, so a
|
|
77
|
+
# result refers to them by name (see _runtime._work).
|
|
78
|
+
self._main_names = sorted(t.__qualname__ for t in types if t.__module__ == "__main__")
|
|
79
|
+
|
|
80
|
+
def __call__(self, *args: Any, **kwargs: Any) -> Any:
|
|
81
|
+
return self._fn(*args, **kwargs)
|
|
82
|
+
|
|
83
|
+
def local(self, *args: Any, **kwargs: Any) -> Any:
|
|
84
|
+
"""Runs the function here, in this process."""
|
|
85
|
+
return self._fn(*args, **kwargs)
|
|
86
|
+
|
|
87
|
+
def _payload(self, args: tuple, kwargs: dict) -> bytes:
|
|
88
|
+
return cloudpickle.dumps(
|
|
89
|
+
{"fn": self._fn, "args": args, "kwargs": kwargs, "trust": self._cfg.trust_results,
|
|
90
|
+
"main_names": self._main_names},
|
|
91
|
+
protocol=5,
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
def _session(self) -> Session:
|
|
95
|
+
check_python(self._cfg.image)
|
|
96
|
+
return Session(self._cfg.client(), self._cfg.spec(self.__name__))
|
|
97
|
+
|
|
98
|
+
def remote(self, *args: Any, **kwargs: Any) -> Any:
|
|
99
|
+
"""Runs the function on a new session and returns what it returned. Blocks until done.
|
|
100
|
+
`last_run` afterwards says what it cost."""
|
|
101
|
+
payload = self._payload(args, kwargs)
|
|
102
|
+
s = self._session()
|
|
103
|
+
released = False
|
|
104
|
+
try:
|
|
105
|
+
s.start()
|
|
106
|
+
return s.call(payload, self._allowed)
|
|
107
|
+
except SessionError as e:
|
|
108
|
+
self.last_run = e.run = s.release()
|
|
109
|
+
released = True
|
|
110
|
+
raise
|
|
111
|
+
finally:
|
|
112
|
+
if not released:
|
|
113
|
+
self.last_run = s.release()
|
|
114
|
+
|
|
115
|
+
def map(self, iterable: Iterable[Any], *, kwargs_list: list[dict] | None = None) -> list:
|
|
116
|
+
"""Runs the function on every item, one after another on one session, and returns the
|
|
117
|
+
results in order. An item that raises does not stop the rest: MapError at the end
|
|
118
|
+
carries every result and every failure."""
|
|
119
|
+
items = list(iterable)
|
|
120
|
+
kwargs_list = kwargs_list or [{} for _ in items]
|
|
121
|
+
if len(kwargs_list) != len(items):
|
|
122
|
+
raise ValueError("kwargs_list must have one entry per item")
|
|
123
|
+
if not items:
|
|
124
|
+
return []
|
|
125
|
+
results: list[Any] = []
|
|
126
|
+
failures: list[tuple[int, BaseException]] = []
|
|
127
|
+
s = self._session()
|
|
128
|
+
info: RunInfo | None = None
|
|
129
|
+
try:
|
|
130
|
+
s.start()
|
|
131
|
+
for i, (item, kw) in enumerate(zip(items, kwargs_list, strict=True)):
|
|
132
|
+
try:
|
|
133
|
+
results.append(s.call(self._payload((item,), kw), self._allowed))
|
|
134
|
+
except (RemoteFunctionError, ResultParseError) as e:
|
|
135
|
+
results.append(None)
|
|
136
|
+
failures.append((i, e))
|
|
137
|
+
except Exception as e:
|
|
138
|
+
info = s.release()
|
|
139
|
+
self.last_run = info
|
|
140
|
+
done = len(results)
|
|
141
|
+
if done == 0:
|
|
142
|
+
if isinstance(e, SessionError):
|
|
143
|
+
e.run = info
|
|
144
|
+
raise
|
|
145
|
+
raise MapError(
|
|
146
|
+
f"map stopped after {done} of {len(items)} items: {e}",
|
|
147
|
+
results=results + [None] * (len(items) - done),
|
|
148
|
+
failures=failures + [(done, e)],
|
|
149
|
+
total=len(items),
|
|
150
|
+
run=info,
|
|
151
|
+
session_id=s.id,
|
|
152
|
+
) from e
|
|
153
|
+
info = s.release()
|
|
154
|
+
self.last_run = info
|
|
155
|
+
if failures:
|
|
156
|
+
raise MapError(f"{len(failures)} of {len(items)} items failed", results=results, failures=failures,
|
|
157
|
+
total=len(items), run=info, session_id=s.id)
|
|
158
|
+
return results
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def function(
|
|
162
|
+
*,
|
|
163
|
+
gpu: str | list[str] | None = None,
|
|
164
|
+
family: str | list[str] | None = None,
|
|
165
|
+
min_vram: int | None = None,
|
|
166
|
+
gpu_count: int = 1,
|
|
167
|
+
image: Image | str | None = None,
|
|
168
|
+
timeout: int = 3600,
|
|
169
|
+
location: str | None = None,
|
|
170
|
+
max_rate: float | None = None,
|
|
171
|
+
env: dict[str, str] | None = None,
|
|
172
|
+
volume: str | dict[str, str] | None = None,
|
|
173
|
+
name: str | None = None,
|
|
174
|
+
result_types: list[type] | None = None,
|
|
175
|
+
trust_results: bool = False,
|
|
176
|
+
host: str | None = None,
|
|
177
|
+
key: str | None = None,
|
|
178
|
+
) -> Callable[[Callable], Function]:
|
|
179
|
+
"""Makes a function run on a Mimiry GPU with `.remote()` and `.map()`.
|
|
180
|
+
|
|
181
|
+
The machine: `gpu` (types, as `mimiry availability` lists them), `family`, `min_vram` (GB),
|
|
182
|
+
`gpu_count`, `location`, `max_rate` (EUR per hour). With none of them, the cheapest GPU.
|
|
183
|
+
|
|
184
|
+
`image` is where it runs: by default Docker Hub's `python:<your version>-slim`, since the
|
|
185
|
+
function loads only on the Python version that sent it. `Image(...).pip_install("torch")`
|
|
186
|
+
adds packages at start. `volume` mounts a volume at /data (or `{name: path}`).
|
|
187
|
+
|
|
188
|
+
The result loads only if its types are allowed: plain data, NumPy arrays and Torch tensors
|
|
189
|
+
always; the classes in the return annotation and in `result_types`; anything with
|
|
190
|
+
`trust_results=True`, which lets whatever runs in the container run code on this machine.
|
|
191
|
+
|
|
192
|
+
@function(gpu="RTX_48G_PCIe", image=Image.python().pip_install("torch"))
|
|
193
|
+
def matmul(n: int) -> float:
|
|
194
|
+
import torch
|
|
195
|
+
a = torch.rand(n, n, device="cuda")
|
|
196
|
+
return float((a @ a).sum())
|
|
197
|
+
|
|
198
|
+
matmul.remote(4096)
|
|
199
|
+
"""
|
|
200
|
+
if volume is None:
|
|
201
|
+
volumes: dict[str, str] = {}
|
|
202
|
+
elif isinstance(volume, str):
|
|
203
|
+
volumes = {volume: "/data"}
|
|
204
|
+
else:
|
|
205
|
+
volumes = dict(volume)
|
|
206
|
+
|
|
207
|
+
def wrap(fn: Callable) -> Function:
|
|
208
|
+
return Function(fn, _Config(
|
|
209
|
+
gpu=_list(gpu), family=_list(family), min_vram=min_vram, gpu_count=gpu_count, image=as_image(image),
|
|
210
|
+
timeout=timeout, location=location, max_rate=max_rate, env=dict(env or {}), volumes=volumes, name=name,
|
|
211
|
+
result_types=list(result_types or []), trust_results=trust_results, host=host, key=key,
|
|
212
|
+
))
|
|
213
|
+
|
|
214
|
+
return wrap
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
@dataclass
|
|
218
|
+
class RunResult:
|
|
219
|
+
"""What `run` returns."""
|
|
220
|
+
|
|
221
|
+
session_id: str | None
|
|
222
|
+
exit_code: int
|
|
223
|
+
stdout: bytes
|
|
224
|
+
stderr: bytes
|
|
225
|
+
info: RunInfo | None = None
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def run(
|
|
229
|
+
command: str,
|
|
230
|
+
*,
|
|
231
|
+
image: Image | str | None = None,
|
|
232
|
+
gpu: str | list[str] | None = None,
|
|
233
|
+
family: str | list[str] | None = None,
|
|
234
|
+
min_vram: int | None = None,
|
|
235
|
+
gpu_count: int = 1,
|
|
236
|
+
timeout: int = 3600,
|
|
237
|
+
location: str | None = None,
|
|
238
|
+
max_rate: float | None = None,
|
|
239
|
+
env: dict[str, str] | None = None,
|
|
240
|
+
volume: str | dict[str, str] | None = None,
|
|
241
|
+
host: str | None = None,
|
|
242
|
+
key: str | None = None,
|
|
243
|
+
) -> RunResult:
|
|
244
|
+
"""Runs a shell command on a new session and returns its exit code and output.
|
|
245
|
+
|
|
246
|
+
r = run("nvidia-smi")
|
|
247
|
+
print(r.stdout.decode())
|
|
248
|
+
"""
|
|
249
|
+
cfg = function(gpu=gpu, family=family, min_vram=min_vram, gpu_count=gpu_count, image=image, timeout=timeout,
|
|
250
|
+
location=location, max_rate=max_rate, env=env, volume=volume, name="mimiry-run", host=host,
|
|
251
|
+
key=key)(lambda: None)._cfg
|
|
252
|
+
s = Session(cfg.client(), cfg.spec("mimiry-run"))
|
|
253
|
+
released = False
|
|
254
|
+
try:
|
|
255
|
+
s.start(check_python=False)
|
|
256
|
+
code, out, err = s.shell(command)
|
|
257
|
+
except SessionError as e:
|
|
258
|
+
e.run = s.release()
|
|
259
|
+
released = True
|
|
260
|
+
raise
|
|
261
|
+
finally:
|
|
262
|
+
if not released:
|
|
263
|
+
info = s.release()
|
|
264
|
+
return RunResult(session_id=s.id, exit_code=code, stdout=out, stderr=err, info=info)
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""The container image a function runs in, and what to install in it at start."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shlex
|
|
6
|
+
import sys
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
|
|
9
|
+
from mimiry import UsageError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def caller_python() -> str:
|
|
13
|
+
"""This interpreter's major.minor: a function travels as a cloudpickle blob, which loads only
|
|
14
|
+
on the same minor version."""
|
|
15
|
+
return f"{sys.version_info[0]}.{sys.version_info[1]}"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def default_image() -> str:
|
|
19
|
+
"""Docker Hub's official Python image for the caller's own version, so the function loads.
|
|
20
|
+
GPU drivers come from the machine; CUDA libraries come with the packages that need them
|
|
21
|
+
(`pip_install("torch")`)."""
|
|
22
|
+
return f"python:{caller_python()}-slim"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass
|
|
26
|
+
class Image:
|
|
27
|
+
"""A container image, plus apt and pip packages installed when the container starts."""
|
|
28
|
+
|
|
29
|
+
uri: str
|
|
30
|
+
_apt: list[str] = field(default_factory=list)
|
|
31
|
+
_pip: list[str] = field(default_factory=list)
|
|
32
|
+
_env: dict[str, str] = field(default_factory=dict)
|
|
33
|
+
_python: str | None = None
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
def from_registry(cls, uri: str) -> "Image":
|
|
37
|
+
return cls(uri=uri)
|
|
38
|
+
|
|
39
|
+
@classmethod
|
|
40
|
+
def python(cls) -> "Image":
|
|
41
|
+
"""The default: the official Python image matching this interpreter."""
|
|
42
|
+
return cls(uri=default_image(), _python=caller_python())
|
|
43
|
+
|
|
44
|
+
def python_version(self, version: str) -> "Image":
|
|
45
|
+
"""Declares the image's Python ("3.12"), so a mismatch is refused before a session is
|
|
46
|
+
created. An undeclared image is checked once the container runs."""
|
|
47
|
+
parts = str(version).strip().split(".")
|
|
48
|
+
if len(parts) < 2 or not all(p.isdigit() for p in parts[:2]):
|
|
49
|
+
raise UsageError(f"python_version must look like '3.12', got {version!r}")
|
|
50
|
+
self._python = f"{int(parts[0])}.{int(parts[1])}"
|
|
51
|
+
return self
|
|
52
|
+
|
|
53
|
+
def pip_install(self, *packages: str) -> "Image":
|
|
54
|
+
self._pip.extend(packages)
|
|
55
|
+
return self
|
|
56
|
+
|
|
57
|
+
def apt_install(self, *packages: str) -> "Image":
|
|
58
|
+
self._apt.extend(packages)
|
|
59
|
+
return self
|
|
60
|
+
|
|
61
|
+
def env(self, **values: str) -> "Image":
|
|
62
|
+
self._env.update(values)
|
|
63
|
+
return self
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def declared_python(self) -> str | None:
|
|
67
|
+
return self._python
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def env_vars(self) -> dict[str, str]:
|
|
71
|
+
return dict(self._env)
|
|
72
|
+
|
|
73
|
+
def install_steps(self) -> str:
|
|
74
|
+
"""The shell commands that install the packages, or "" when there are none."""
|
|
75
|
+
steps = []
|
|
76
|
+
if self._apt:
|
|
77
|
+
pkgs = " ".join(shlex.quote(p) for p in self._apt)
|
|
78
|
+
steps.append(
|
|
79
|
+
"apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -q "
|
|
80
|
+
f"--no-install-recommends {pkgs}"
|
|
81
|
+
)
|
|
82
|
+
if self._pip:
|
|
83
|
+
pkgs = " ".join(shlex.quote(p) for p in self._pip)
|
|
84
|
+
steps.append(f"python3 -m pip install --quiet --no-input --break-system-packages {pkgs}")
|
|
85
|
+
return " && ".join(steps)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def as_image(image: "Image | str | None") -> Image:
|
|
89
|
+
if image is None:
|
|
90
|
+
return Image.python()
|
|
91
|
+
if isinstance(image, Image):
|
|
92
|
+
return image
|
|
93
|
+
return Image.from_registry(image)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def check_python(image: Image) -> None:
|
|
97
|
+
"""Refuses, before anything is paid for, an image whose declared Python cannot load the call."""
|
|
98
|
+
declared, caller = image.declared_python, caller_python()
|
|
99
|
+
if declared is not None and declared != caller:
|
|
100
|
+
raise UsageError(
|
|
101
|
+
f"image {image.uri!r} runs Python {declared}, and this script runs on Python {caller}: "
|
|
102
|
+
"a function travels as a cloudpickle blob, which loads only on the same minor version. "
|
|
103
|
+
f"Use an image with Python {caller} (the default, python:{caller}-slim, has it)."
|
|
104
|
+
)
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Loading a result from the container, checked against an allow-list (RC-473, decision S1).
|
|
2
|
+
|
|
3
|
+
A pickled result names the functions and classes that rebuild it, and loading it calls them: an
|
|
4
|
+
unchecked result can run anything on this machine. Whatever can write the result can try that:
|
|
5
|
+
the function, its dependencies, the image, or anyone who breaks into the container. So a result
|
|
6
|
+
loads only if every name in it is on the allow-list:
|
|
7
|
+
|
|
8
|
+
- the defaults below: constructors that build data and do nothing else;
|
|
9
|
+
- the classes in the function's return annotation, and their dataclass fields' types;
|
|
10
|
+
- the classes the caller names in `result_types`.
|
|
11
|
+
|
|
12
|
+
`trust_results=True` loads anything, for results an allow-list cannot describe.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import dataclasses
|
|
18
|
+
import io
|
|
19
|
+
import pickle
|
|
20
|
+
import typing
|
|
21
|
+
from typing import Any, Callable, Iterable
|
|
22
|
+
|
|
23
|
+
from ._errors import ResultTypeRefused
|
|
24
|
+
|
|
25
|
+
#: (module, name) pairs any result may use. Plain data only: never a function that reads a
|
|
26
|
+
#: file, imports, evaluates or loads another pickle.
|
|
27
|
+
DEFAULT_ALLOWED: frozenset[tuple[str, str]] = frozenset(
|
|
28
|
+
{
|
|
29
|
+
("builtins", n)
|
|
30
|
+
for n in ("set", "frozenset", "complex", "bytearray", "range", "slice", "list", "dict", "tuple", "int",
|
|
31
|
+
"float", "str", "bytes", "bool")
|
|
32
|
+
}
|
|
33
|
+
| {("datetime", n) for n in ("datetime", "date", "time", "timedelta", "timezone")}
|
|
34
|
+
| {
|
|
35
|
+
("decimal", "Decimal"),
|
|
36
|
+
("fractions", "Fraction"),
|
|
37
|
+
("uuid", "UUID"),
|
|
38
|
+
("collections", "OrderedDict"),
|
|
39
|
+
("collections", "deque"),
|
|
40
|
+
("collections", "Counter"),
|
|
41
|
+
("collections", "defaultdict"),
|
|
42
|
+
("pathlib", "PurePosixPath"),
|
|
43
|
+
}
|
|
44
|
+
# NumPy arrays, scalars and dtypes, under NumPy 1 and NumPy 2 names (the container's and the
|
|
45
|
+
# caller's versions may differ).
|
|
46
|
+
| {
|
|
47
|
+
(m, n)
|
|
48
|
+
for m in ("numpy.core.multiarray", "numpy._core.multiarray")
|
|
49
|
+
for n in ("_reconstruct", "scalar")
|
|
50
|
+
}
|
|
51
|
+
| {(m, "_frombuffer") for m in ("numpy.core.numeric", "numpy._core.numeric")}
|
|
52
|
+
| {("numpy", "ndarray"), ("numpy", "dtype")}
|
|
53
|
+
# Torch tensors travel as bytes, dtype and shape (see _runtime._reduce_tensor): Torch's own
|
|
54
|
+
# form calls torch.load on this side, which can run anything.
|
|
55
|
+
| {("mimiry_serverless._runtime", "rebuild_tensor")}
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _name(cls: type) -> tuple[str, str]:
|
|
60
|
+
return (cls.__module__, cls.__qualname__)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _ignorable(t: Any) -> bool:
|
|
64
|
+
return t is Any or t is object or t is type(None) or isinstance(t, typing.TypeVar)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def types_from_annotation(fn: Callable) -> set[type]:
|
|
68
|
+
"""The classes a function's return annotation names: generics opened (list[Point] gives
|
|
69
|
+
Point), and a dataclass's fields' types one level down. `Any` and `object` add nothing."""
|
|
70
|
+
try:
|
|
71
|
+
hints = typing.get_type_hints(fn)
|
|
72
|
+
except Exception:
|
|
73
|
+
return set()
|
|
74
|
+
found: set[type] = set()
|
|
75
|
+
|
|
76
|
+
def visit(t: Any, depth: int) -> None:
|
|
77
|
+
if _ignorable(t):
|
|
78
|
+
return
|
|
79
|
+
for arg in typing.get_args(t):
|
|
80
|
+
visit(arg, depth)
|
|
81
|
+
origin = typing.get_origin(t)
|
|
82
|
+
if origin is not None:
|
|
83
|
+
return
|
|
84
|
+
if not isinstance(t, type) or t.__module__ == "builtins":
|
|
85
|
+
return
|
|
86
|
+
if t in found:
|
|
87
|
+
return
|
|
88
|
+
found.add(t)
|
|
89
|
+
if depth == 0 and dataclasses.is_dataclass(t):
|
|
90
|
+
try:
|
|
91
|
+
field_hints = typing.get_type_hints(t)
|
|
92
|
+
except Exception:
|
|
93
|
+
field_hints = {}
|
|
94
|
+
for ft in field_hints.values():
|
|
95
|
+
visit(ft, 1)
|
|
96
|
+
|
|
97
|
+
if "return" in hints:
|
|
98
|
+
visit(hints["return"], 0)
|
|
99
|
+
return found
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class _CheckedUnpickler(pickle.Unpickler):
|
|
103
|
+
def __init__(self, data: bytes, allowed: frozenset[tuple[str, str]]):
|
|
104
|
+
super().__init__(io.BytesIO(data))
|
|
105
|
+
self._allowed = allowed
|
|
106
|
+
|
|
107
|
+
def find_class(self, module: str, name: str) -> Any:
|
|
108
|
+
if (module, name) in self._allowed:
|
|
109
|
+
return super().find_class(module, name)
|
|
110
|
+
raise ResultTypeRefused(module, name)
|
|
111
|
+
|
|
112
|
+
def persistent_load(self, pid: Any) -> Any:
|
|
113
|
+
raise ResultTypeRefused("persistent id", repr(pid)[:80])
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def allowed_names(types: Iterable[type]) -> frozenset[tuple[str, str]]:
|
|
117
|
+
return DEFAULT_ALLOWED | {_name(t) for t in types}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def load(data: bytes, allowed: frozenset[tuple[str, str]] | None) -> Any:
|
|
121
|
+
"""Loads a result. `allowed=None` trusts it (trust_results=True)."""
|
|
122
|
+
if allowed is None:
|
|
123
|
+
return pickle.loads(data)
|
|
124
|
+
return _CheckedUnpickler(data, allowed).load()
|