oprunner 0.1.0.dev0__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.
oprunner/host.py ADDED
@@ -0,0 +1,281 @@
1
+ """What a front end in another language asks oprunner for.
2
+
3
+ An in-process front end reads ``OpSpec`` as a Python object and calls
4
+ ``opspec.plan.plan`` directly. A front end in another language cannot: it reaches
5
+ oprunner over Appose, so everything it needs has to be expressible as JSON. This
6
+ module is that surface, and nothing else belongs in it.
7
+
8
+ Three things live here:
9
+
10
+ * the **strings** an out-of-process host needs in order to drive a worker at
11
+ all -- the service init script and the task script it posts. They are data
12
+ rather than something each front end transcribes, so that changing how a
13
+ worker is started changes one place instead of one place per language;
14
+ * ``describe``, which is ``discover`` with its result flattened to JSON;
15
+ * ``plan``, which is ``opspec.plan.plan`` reached by op name rather than by function
16
+ object, so that the axis arithmetic is computed once here rather than
17
+ reimplemented in every host language.
18
+
19
+ Like the rest of oprunner's core this module is austere -- standard library only
20
+ -- because the service that answers these questions runs in the ``minimal``
21
+ environment, and because ``discover`` importing an op module is the whole
22
+ point: an op that will not load in a minimal environment must be reported,
23
+ not crash the description.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import importlib
29
+ from pathlib import Path
30
+ from typing import Any
31
+
32
+ from opspec.op import COMPUTER, FUNCTION, INPLACE, WIRE_TYPES, Role, is_op
33
+
34
+ from . import _adapt
35
+
36
+ # The script sent for every op call. Its last statement is an expression
37
+ # yielding a dict, which Appose turns into the task's outputs.
38
+ CALL = "skop_invoke(task, module, function, kwargs, plans, origin)"
39
+
40
+ # Installed into every op worker via the service init script. Names defined
41
+ # here become worker exports, and so are in scope for every task.
42
+ #
43
+ # NB: The search path is extended here rather than via PYTHONPATH. Appose
44
+ # gained per-service env vars in 0.12; setting them on the builder instead
45
+ # would fold a machine-specific path into the environment's identity, causing
46
+ # a rebuild whenever the checkout moves.
47
+ #
48
+ # The insertion is at position 0, so a checkout shadows the copy of oprunner that
49
+ # the environment installs. That is deliberate: a developer editing an op sees
50
+ # the edit without bumping the pin every environment's identity depends on.
51
+ # NB: MPLBACKEND is dropped because a worker inherits its caller's environment,
52
+ # and a Jupyter kernel sets MPLBACKEND=module://matplotlib_inline.backend_inline
53
+ # to get inline plots. matplotlib reads it at import and raises if it names a
54
+ # backend it cannot load -- and matplotlib_inline is a Jupyter package no op
55
+ # environment carries.
56
+ #
57
+ # So an op that imports pyplot (ultralytics does, deep in its chain) died from a
58
+ # notebook and worked from a script, surviving only where something had pulled
59
+ # matplotlib_inline in transitively. Popped before any op module is imported;
60
+ # nothing in a worker draws, so none needs a backend chosen by its caller.
61
+ INIT = """
62
+ import os
63
+ import sys
64
+ os.environ.pop("MPLBACKEND", None)
65
+ sys.path.insert(0, {root!r})
66
+ import numpy # NB: must precede the worker's I/O loop on Windows.
67
+ import oprunner.worker
68
+ skop_invoke = oprunner.worker.invoke
69
+ """
70
+
71
+ # Installed into the one service that answers metadata questions. It runs in
72
+ # the minimal environment and never touches numpy or an op's dependencies.
73
+ METADATA_INIT = """
74
+ import sys
75
+ sys.path.insert(0, {root!r})
76
+ import oprunner.host
77
+ skop_describe = oprunner.host.describe
78
+ skop_plan = oprunner.host.plan
79
+ skop_constants = oprunner.host.constants
80
+ """
81
+
82
+ # The same two scripts, appending rather than inserting.
83
+ #
84
+ # `root` is only worth putting first when it is a checkout, which is the case
85
+ # the shadowing above exists for. When oprunner is installed normally, `root` is
86
+ # the host's site-packages -- and putting *that* first hands the worker every
87
+ # package the host has, built for the host's Python. A worker on a different
88
+ # Python then fails at `import numpy`, before skop_invoke is ever defined, and
89
+ # reports only `NameError: name 'skop_invoke' is not defined`.
90
+ #
91
+ # Appending keeps the one case that still needs the path: envs/unseg-cv has no
92
+ # pinned scikit-ops at all, because scikit-ops requires Python 3.10 and UNSEG's
93
+ # pins 3.9, so it reaches oprunner through this path alone. Last on sys.path is
94
+ # enough for that, and lets every environment that does install oprunner use its
95
+ # own copy.
96
+ INIT_APPEND = """
97
+ import os
98
+ import sys
99
+ os.environ.pop("MPLBACKEND", None)
100
+ sys.path.append({root!r})
101
+ import numpy # NB: must precede the worker's I/O loop on Windows.
102
+ import oprunner.worker
103
+ skop_invoke = oprunner.worker.invoke
104
+ """
105
+
106
+ METADATA_INIT_APPEND = """
107
+ import sys
108
+ sys.path.append({root!r})
109
+ import oprunner.host
110
+ skop_describe = oprunner.host.describe
111
+ skop_plan = oprunner.host.plan
112
+ skop_constants = oprunner.host.constants
113
+ """
114
+
115
+ DESCRIBE = "skop_describe(package)"
116
+ PLAN = "skop_plan(op, param, shape, axes, position, mapping, dispositions)"
117
+
118
+
119
+ def is_checkout(root: Path | str) -> bool:
120
+ """Whether *root* is a source tree rather than an install directory.
121
+
122
+ A checkout's ``root`` holds only oprunner, so putting it first on a worker's
123
+ ``sys.path`` shadows nothing else. An install's ``root`` is the host's
124
+ site-packages, which holds everything -- see the note on ``INIT_APPEND``.
125
+
126
+ Compared against this interpreter's own package directories rather than
127
+ matched by name, because "site-packages" is not the only spelling: a
128
+ virtualenv, a conda env and a Debian system install each place them
129
+ differently.
130
+ """
131
+ import sysconfig
132
+
133
+ root = Path(root).resolve()
134
+ installed = {
135
+ Path(path).resolve()
136
+ for key in ("purelib", "platlib")
137
+ if (path := sysconfig.get_paths().get(key))
138
+ }
139
+ return root not in installed
140
+
141
+
142
+ def init_script(root: Path | str, metadata: bool = False) -> str:
143
+ """The init script for a worker, given where this oprunner lives.
144
+
145
+ Chooses between inserting and appending ``root``; see ``INIT_APPEND``.
146
+ """
147
+ if is_checkout(root):
148
+ template = METADATA_INIT if metadata else INIT
149
+ else:
150
+ template = METADATA_INIT_APPEND if metadata else INIT_APPEND
151
+ return template.format(root=str(root))
152
+
153
+
154
+ CONSTANTS = "skop_constants()"
155
+
156
+
157
+ def constants() -> dict:
158
+ """The scripts a host needs in order to drive workers.
159
+
160
+ A host transcribes only enough to start *this* service; everything it
161
+ uses afterwards it reads from here.
162
+ """
163
+ return {
164
+ "init": INIT,
165
+ "call": CALL,
166
+ "metadata_init": METADATA_INIT,
167
+ # Additive: a host that only knows the two above keeps the behaviour
168
+ # it had. One that can tell a checkout from an install should prefer
169
+ # these when oprunner is installed -- see the note on INIT_APPEND.
170
+ "init_append": INIT_APPEND,
171
+ "metadata_init_append": METADATA_INIT_APPEND,
172
+ "describe": DESCRIBE,
173
+ "plan": PLAN,
174
+ "wire_types": list(WIRE_TYPES),
175
+ "roles": [role.value for role in Role],
176
+ "dispositions": list(_adapt.DISPOSITIONS),
177
+ "forms": [FUNCTION, COMPUTER, INPLACE],
178
+ }
179
+
180
+
181
+ def describe(package: str = "skop.ops") -> dict:
182
+ """Every op in a collection, and every module that would not load.
183
+
184
+ Failures are part of the answer rather than an exception, for the same
185
+ reason ``discover`` collects them: an environment missing one dependency
186
+ must still yield the other fifty-eight ops.
187
+ """
188
+ from .discovery import discover
189
+
190
+ specs, failures = discover(package)
191
+ return {
192
+ "package": package,
193
+ "ops": [spec.to_dict() for spec in specs],
194
+ "failures": [
195
+ {
196
+ "module": failure.module,
197
+ "error": failure.error,
198
+ "heavy_imports": list(failure.heavy_imports),
199
+ "message": str(failure),
200
+ }
201
+ for failure in failures
202
+ ],
203
+ }
204
+
205
+
206
+ def plan(
207
+ op: str,
208
+ param: str,
209
+ shape: list,
210
+ axes: list,
211
+ position: dict | None = None,
212
+ mapping: list | None = None,
213
+ dispositions: dict | None = None,
214
+ ) -> dict:
215
+ """Fit an array to an op's declared axes, by op name rather than function.
216
+
217
+ Args:
218
+ op: The op's ID, ``"<module>:<function>"`` -- the same string
219
+ ``OpSpec.name`` carries, treated as opaque.
220
+ param: Name of the parameter the array is destined for.
221
+ shape: The array's shape.
222
+ axes: What that array's axes actually are, one label per axis. A host
223
+ works this out for itself; oprunner does not guess. ``None`` in place
224
+ of a label means that axis has no name.
225
+
226
+ **Order matters, and it is numpy's**: last axis fastest-moving. A
227
+ host whose own arrays are x-fastest -- ImgLib2's are -- reverses
228
+ its axis list before it gets here. Nothing downstream can detect
229
+ the mistake, because a transposed array is still a valid array.
230
+ position: Current position along each axis, keyed by axis name or
231
+ index, for any axis being indexed down to a single plane.
232
+ mapping: One input-axis index (or None) per declared slot, overriding
233
+ oprunner's own assignment.
234
+ dispositions: What to do with each leftover axis, keyed by axis index
235
+ as a string or an int: ``"iterate"``, ``"select"`` or ``"pass"``.
236
+
237
+ Returns:
238
+ The plan, as ``AdaptationPlan.to_dict`` gives it -- warnings included.
239
+ Raises only when no mapping could work at all.
240
+ """
241
+ fn = op_function(op)
242
+ return _adapt.plan(
243
+ fn,
244
+ param,
245
+ tuple(shape),
246
+ [None if label is None else str(label) for label in axes],
247
+ _int_keyed(position),
248
+ None if mapping is None else list(mapping),
249
+ _int_keyed(dispositions),
250
+ ).to_dict()
251
+
252
+
253
+ def op_function(op: str) -> Any:
254
+ """Resolve an op ID to the function it names.
255
+
256
+ The ID is opaque to a host, but not to oprunner: it is ``module:function``,
257
+ and this is the one place that says so.
258
+ """
259
+ module_name, _, function_name = op.partition(":")
260
+ if not module_name or not function_name:
261
+ raise ValueError(f"Not an op ID: {op!r}. Expected '<module>:<function>'.")
262
+ fn = getattr(importlib.import_module(module_name), function_name, None)
263
+ if fn is None or not is_op(fn):
264
+ raise ValueError(f"No op named {op!r}")
265
+ return fn
266
+
267
+
268
+ def _int_keyed(mapping: dict | None) -> dict | None:
269
+ """Restore integer keys that JSON turned into strings.
270
+
271
+ Both ``position`` and ``dispositions`` are keyed by axis index, and JSON
272
+ object keys are strings, so ``{0: "iterate"}`` arrives as
273
+ ``{"0": "iterate"}``. ``position`` may legitimately be keyed by axis
274
+ *name* as well, so only the numeric-looking keys are converted.
275
+ """
276
+ if mapping is None:
277
+ return None
278
+ return {
279
+ int(key) if isinstance(key, str) and key.lstrip("-").isdigit() else key: value
280
+ for key, value in mapping.items()
281
+ }