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/__init__.py +49 -0
- oprunner/_adapt.py +198 -0
- oprunner/_codec.py +126 -0
- oprunner/_tiling.py +400 -0
- oprunner/discovery.py +126 -0
- oprunner/host.py +281 -0
- oprunner/runner.py +901 -0
- oprunner/worker.py +158 -0
- oprunner-0.1.0.dev0.dist-info/METADATA +33 -0
- oprunner-0.1.0.dev0.dist-info/RECORD +12 -0
- oprunner-0.1.0.dev0.dist-info/WHEEL +4 -0
- oprunner-0.1.0.dev0.dist-info/licenses/LICENSE +24 -0
oprunner/_tiling.py
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
"""Running an op tile by tile, on the host.
|
|
2
|
+
|
|
3
|
+
opspec plans the tiles (``opspec.tiling``); this carries a plan out. Each
|
|
4
|
+
tile is read from the input as numpy -- the input itself may be a zarr or
|
|
5
|
+
dask array that never fits in memory whole -- handed to the op through the
|
|
6
|
+
ordinary call path, and its result is written into the output: cropped to the
|
|
7
|
+
tile's core, or blended into its neighbours across the overlap. The op sees plain numpy and knows nothing of tiles,
|
|
8
|
+
and the host never holds more than one tile's input and result at a time.
|
|
9
|
+
|
|
10
|
+
The loop runs on the host, so each tile is one round trip to the worker.
|
|
11
|
+
That is negligible for a handful of large tiles, which is what a memory
|
|
12
|
+
budget produces; an op cut into thousands of small ones tiles itself
|
|
13
|
+
(docs/design/0017-memory-and-tiled-processing/tiling.md).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import shutil
|
|
19
|
+
import subprocess
|
|
20
|
+
import tempfile
|
|
21
|
+
from collections.abc import Callable
|
|
22
|
+
from dataclasses import dataclass
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
import numpy as np
|
|
27
|
+
|
|
28
|
+
from opspec.op import OpSpec
|
|
29
|
+
from opspec.tiling import TilePlan, parse_bytes, plan_tiles
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"DEFAULT_FRACTION",
|
|
33
|
+
"Tiler",
|
|
34
|
+
"default_budget",
|
|
35
|
+
"gpu_free",
|
|
36
|
+
"prepare_out",
|
|
37
|
+
"run_tiles",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
#: How tiles can be put back together. None means crop.
|
|
41
|
+
MERGES = (None, "crop", "blend")
|
|
42
|
+
|
|
43
|
+
#: The share of the memory free right now that an op may have by default.
|
|
44
|
+
DEFAULT_FRACTION = 0.85
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def default_budget(
|
|
48
|
+
fraction: float = DEFAULT_FRACTION, device: str = "cpu"
|
|
49
|
+
) -> int | None:
|
|
50
|
+
"""The memory an op may use, when the caller names no budget.
|
|
51
|
+
|
|
52
|
+
For ``device="cpu"``, *fraction* of what is available right now: what the
|
|
53
|
+
machine has free, or, when this process runs inside a memory-limited
|
|
54
|
+
cgroup -- under ``systemd-run -p MemoryMax=``, a Slurm job, a container --
|
|
55
|
+
the room left in it, whichever is less. The machine's own figure knows
|
|
56
|
+
nothing of the cgroup, and the cgroup's limit is the one that kills.
|
|
57
|
+
|
|
58
|
+
For ``device="gpu"``, *fraction* of the GPU's free memory (``gpu_free``),
|
|
59
|
+
or None when that cannot be found out -- and then nothing is tiled.
|
|
60
|
+
"""
|
|
61
|
+
if device == "gpu":
|
|
62
|
+
free = gpu_free()
|
|
63
|
+
return None if free is None else max(0, int(fraction * free))
|
|
64
|
+
|
|
65
|
+
import psutil
|
|
66
|
+
|
|
67
|
+
available = psutil.virtual_memory().available
|
|
68
|
+
room = _cgroup_headroom()
|
|
69
|
+
if room is not None:
|
|
70
|
+
available = min(available, room)
|
|
71
|
+
return max(0, int(fraction * available))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def gpu_free() -> int | None:
|
|
75
|
+
"""Bytes free on the first NVIDIA GPU, or None if there is none to ask.
|
|
76
|
+
|
|
77
|
+
Asked of ``nvidia-smi``, so the host needs no CUDA library of its own:
|
|
78
|
+
the op's environment has cupy, and the host does not. The first GPU is
|
|
79
|
+
the one an op uses unless told otherwise.
|
|
80
|
+
"""
|
|
81
|
+
if shutil.which("nvidia-smi") is None:
|
|
82
|
+
return None
|
|
83
|
+
try:
|
|
84
|
+
text = subprocess.run(
|
|
85
|
+
["nvidia-smi", "--query-gpu=memory.free", "--format=csv,noheader,nounits"],
|
|
86
|
+
capture_output=True,
|
|
87
|
+
text=True,
|
|
88
|
+
timeout=10,
|
|
89
|
+
check=True,
|
|
90
|
+
).stdout
|
|
91
|
+
except (OSError, subprocess.SubprocessError):
|
|
92
|
+
return None
|
|
93
|
+
free = _parse_nvidia_smi(text)
|
|
94
|
+
return free[0] if free else None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _parse_nvidia_smi(text: str) -> list[int]:
|
|
98
|
+
"""Bytes free per GPU, from ``nvidia-smi --query-gpu=memory.free``'s MiB."""
|
|
99
|
+
return [int(line) * 1024**2 for line in text.split() if line.strip().isdigit()]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@dataclass(frozen=True)
|
|
103
|
+
class Tiler:
|
|
104
|
+
"""The caller's tiling choices, in one object; see tiling.md in 0017.
|
|
105
|
+
|
|
106
|
+
The op declares hints (``@op(tile=..., peak_memory=...)``); these are
|
|
107
|
+
what a caller, or a user in a GUI, decides on top of them::
|
|
108
|
+
|
|
109
|
+
Tiler() # the defaults
|
|
110
|
+
Tiler(memory=0.5) # half the free memory
|
|
111
|
+
Tiler(memory="2G", overlap=16) # a set budget, and a smaller overlap
|
|
112
|
+
Tiler(tile_shape=(64, 512, 512))
|
|
113
|
+
Tiler.off() # never tile
|
|
114
|
+
|
|
115
|
+
``memory`` is a fraction of the free memory of the op's device -- RAM,
|
|
116
|
+
or the GPU's for an op whose ``PeakMemory`` says ``device="gpu"`` -- or
|
|
117
|
+
a size, in bytes or as ``"2G"``. ``overlap`` and ``tile_shape`` override
|
|
118
|
+
the op's hint and the budget's choice. ``plan`` turns all of it into the
|
|
119
|
+
tiles for one call, which a front end shows and the runner then follows.
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
memory: float | int | str | None = None
|
|
123
|
+
overlap: int | tuple[int, ...] | None = None
|
|
124
|
+
tile_shape: tuple[int, ...] | None = None
|
|
125
|
+
enabled: bool = True
|
|
126
|
+
|
|
127
|
+
@classmethod
|
|
128
|
+
def off(cls) -> Tiler:
|
|
129
|
+
"""A Tiler that never tiles."""
|
|
130
|
+
return cls(enabled=False)
|
|
131
|
+
|
|
132
|
+
def budget(self, device: str = "cpu") -> int | None:
|
|
133
|
+
"""The memory budget, in bytes, for an op on *device*; None if unknown."""
|
|
134
|
+
if self.memory is None:
|
|
135
|
+
return default_budget(DEFAULT_FRACTION, device)
|
|
136
|
+
if isinstance(self.memory, float) and 0 < self.memory <= 1:
|
|
137
|
+
return default_budget(self.memory, device)
|
|
138
|
+
return parse_bytes(self.memory)
|
|
139
|
+
|
|
140
|
+
def plan(self, op: Any, args: dict) -> TilePlan | None:
|
|
141
|
+
"""How this call is cut up, or None when it is not tiled at all.
|
|
142
|
+
|
|
143
|
+
None when tiling is off, the op declares no hints, or the budget for
|
|
144
|
+
its device cannot be found out. A plan of one tile means it fits.
|
|
145
|
+
"""
|
|
146
|
+
spec = op if isinstance(op, OpSpec) else OpSpec.from_op(op)
|
|
147
|
+
if not (self.enabled and spec.tile and spec.peak_memory):
|
|
148
|
+
return None
|
|
149
|
+
if spec.merge not in MERGES:
|
|
150
|
+
raise NotImplementedError(
|
|
151
|
+
f"Op {spec.name}: merging tiles by {spec.merge!r} is not "
|
|
152
|
+
f"implemented; only {' and '.join(MERGES[1:])} are"
|
|
153
|
+
)
|
|
154
|
+
peak = spec.peak_memory
|
|
155
|
+
budget = self.budget(peak.device)
|
|
156
|
+
if budget is None:
|
|
157
|
+
return None
|
|
158
|
+
# The first tiled input sets the shape; any others are tiled the same.
|
|
159
|
+
image = args[spec.tile[0]]
|
|
160
|
+
values = {p.name: p.default for p in spec.params if not p.required}
|
|
161
|
+
values.update(args)
|
|
162
|
+
if self.overlap is not None:
|
|
163
|
+
overlap = self.overlap
|
|
164
|
+
else:
|
|
165
|
+
overlap = spec.overlap.resolve(values) if spec.overlap else 0
|
|
166
|
+
if spec.pad is None:
|
|
167
|
+
pad = 0
|
|
168
|
+
elif spec.pad.param and values.get(spec.pad.param) is None and self.overlap:
|
|
169
|
+
# Not made yet -- a workflow makes its PSF partway through -- so
|
|
170
|
+
# assume the op pads by the overlap. The run plans again with the
|
|
171
|
+
# real one.
|
|
172
|
+
pad = self.overlap
|
|
173
|
+
else:
|
|
174
|
+
pad = spec.pad.resolve(values)
|
|
175
|
+
# The copies a tile makes on its way: read on the host, into shared
|
|
176
|
+
# memory for the worker, and its result back the same way. They are
|
|
177
|
+
# in RAM, so they count against a RAM budget only; a GPU op's budget
|
|
178
|
+
# is the GPU's. The result's dtype is not known until it exists; the
|
|
179
|
+
# op's working dtype is the best guess.
|
|
180
|
+
item_in = np.dtype(image.dtype).itemsize
|
|
181
|
+
item_out = np.dtype(peak.dtype or image.dtype).itemsize
|
|
182
|
+
extra = 0 if peak.device == "gpu" else 2 * item_in + 2 * item_out
|
|
183
|
+
return plan_tiles(
|
|
184
|
+
image.shape,
|
|
185
|
+
image.dtype,
|
|
186
|
+
peak,
|
|
187
|
+
budget,
|
|
188
|
+
overlap,
|
|
189
|
+
axes=_split_axes(spec, image.ndim),
|
|
190
|
+
extra=extra,
|
|
191
|
+
pad=pad,
|
|
192
|
+
tile_shape=self.tile_shape,
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _split_axes(spec: OpSpec, ndim: int) -> list[int] | None:
|
|
197
|
+
"""Which of the input's axes ``@op(split=...)`` lets a tile be cut along.
|
|
198
|
+
|
|
199
|
+
The names are the tiled input's Axes, matched to the input from the right,
|
|
200
|
+
so Axes("z?", "y", "x") reads a volume as z, y, x and a plane as y, x. An
|
|
201
|
+
input with no axis names to match against may be cut along any axis.
|
|
202
|
+
"""
|
|
203
|
+
if not spec.split:
|
|
204
|
+
return None
|
|
205
|
+
param = next(p for p in spec.params if p.name == spec.tile[0])
|
|
206
|
+
if param.axes is None or param.axes.variadic or ndim > len(param.axes.names):
|
|
207
|
+
return None
|
|
208
|
+
names = param.axes.names[len(param.axes.names) - ndim :]
|
|
209
|
+
return [axis for axis, name in enumerate(names) if name in spec.split]
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _cgroup_headroom(
|
|
213
|
+
root: Path = Path("/sys/fs/cgroup"), proc: Path = Path("/proc/self/cgroup")
|
|
214
|
+
) -> int | None:
|
|
215
|
+
"""Bytes left before this process's cgroup, or one above it, is full.
|
|
216
|
+
|
|
217
|
+
cgroup v2 only. A limit can sit on any ancestor -- Slurm sets it on the
|
|
218
|
+
job, one level above the step a program runs in -- so every level is
|
|
219
|
+
read, and the tightest wins. None when there is no limit, or no cgroup
|
|
220
|
+
v2 to read.
|
|
221
|
+
"""
|
|
222
|
+
try:
|
|
223
|
+
line = next(
|
|
224
|
+
entry for entry in proc.read_text().splitlines() if entry.startswith("0::")
|
|
225
|
+
)
|
|
226
|
+
except (OSError, StopIteration):
|
|
227
|
+
return None
|
|
228
|
+
group = root / line[3:].strip().lstrip("/")
|
|
229
|
+
room = None
|
|
230
|
+
while True:
|
|
231
|
+
try:
|
|
232
|
+
limit = (group / "memory.max").read_text().strip()
|
|
233
|
+
if limit != "max":
|
|
234
|
+
left = int(limit) - int((group / "memory.current").read_text())
|
|
235
|
+
room = left if room is None else min(room, left)
|
|
236
|
+
except (OSError, ValueError):
|
|
237
|
+
pass # No memory controller at this level, or no file to read.
|
|
238
|
+
if group == root or group.parent == group:
|
|
239
|
+
return room
|
|
240
|
+
group = group.parent
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def run_tiles(
|
|
244
|
+
call: Callable[[Any], Any],
|
|
245
|
+
image: Any,
|
|
246
|
+
plan: TilePlan,
|
|
247
|
+
out: Any = None,
|
|
248
|
+
room: int | None = None,
|
|
249
|
+
merge: str | None = "crop",
|
|
250
|
+
) -> Any:
|
|
251
|
+
"""Call *call* on each tile of *image*, and put the results together.
|
|
252
|
+
|
|
253
|
+
Args:
|
|
254
|
+
call: Runs the op on one tile and returns its result. It is given the
|
|
255
|
+
tile as numpy, or, when *image* is a dict, a dict of tiles.
|
|
256
|
+
image: The whole input: numpy, or anything that slices into numpy.
|
|
257
|
+
Or a dict of inputs, all tiled the same way -- an image and
|
|
258
|
+
its mask, say. A ``None`` in the dict is passed through as
|
|
259
|
+
``None``: an optional input nobody gave.
|
|
260
|
+
plan: From ``opspec.tiling.plan_tiles``.
|
|
261
|
+
out: Where the result goes; see ``prepare_out``.
|
|
262
|
+
room: Bytes the whole result may take in memory, when it goes to no
|
|
263
|
+
*out*. By default what the plan's budget leaves beside its
|
|
264
|
+
tiles; a GPU op's budget is the GPU's, so its caller says.
|
|
265
|
+
merge: ``"crop"`` keeps each tile's core. ``"blend"`` fades each
|
|
266
|
+
tile out across the overlap and adds them, so neighbours mix
|
|
267
|
+
smoothly where they meet; it needs a float result.
|
|
268
|
+
|
|
269
|
+
Returns:
|
|
270
|
+
The whole result: *out*, if given. Otherwise a numpy array when it
|
|
271
|
+
fits beside the tiles in the budget, and a ``numpy.memmap`` backed by
|
|
272
|
+
a temporary ``.npy`` file when it does not.
|
|
273
|
+
"""
|
|
274
|
+
several = isinstance(image, dict)
|
|
275
|
+
inputs = image if several else {"input": image}
|
|
276
|
+
for name, value in inputs.items():
|
|
277
|
+
if value is not None and tuple(value.shape) != plan.shape:
|
|
278
|
+
raise ValueError(
|
|
279
|
+
f"{name} has shape {tuple(value.shape)}, but the tiles are "
|
|
280
|
+
f"planned for {plan.shape}. Inputs tiled together must match in shape."
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
blend = merge == "blend"
|
|
284
|
+
weights = _blend_weights(plan) if blend else None
|
|
285
|
+
output = None
|
|
286
|
+
for number, tile in enumerate(plan.tiles, 1):
|
|
287
|
+
pieces = {
|
|
288
|
+
name: None if value is None else np.asarray(value[tile.read])
|
|
289
|
+
for name, value in inputs.items()
|
|
290
|
+
}
|
|
291
|
+
result = np.asarray(call(pieces if several else pieces["input"]))
|
|
292
|
+
shape = next(p.shape for p in pieces.values() if p is not None)
|
|
293
|
+
if result.shape != shape:
|
|
294
|
+
raise ValueError(
|
|
295
|
+
f"Tile {number} of {plan.calls}: the op returned shape "
|
|
296
|
+
f"{result.shape} for an input of shape {shape}. Cropping "
|
|
297
|
+
"tiles back together needs a result the shape of its input."
|
|
298
|
+
)
|
|
299
|
+
if blend and not np.issubdtype(result.dtype, np.floating):
|
|
300
|
+
raise ValueError(
|
|
301
|
+
f"Blending tiles needs a float result; the op returned {result.dtype}"
|
|
302
|
+
)
|
|
303
|
+
if output is None and out is not None:
|
|
304
|
+
output = prepare_out(out, plan.shape, result.dtype)
|
|
305
|
+
if blend:
|
|
306
|
+
output[...] = 0 # tiles are added into it
|
|
307
|
+
elif output is None:
|
|
308
|
+
# The tiles' own cost is already planned into the budget; the
|
|
309
|
+
# whole output stays in memory only if it fits beside that.
|
|
310
|
+
if room is None:
|
|
311
|
+
room = plan.budget - plan.peak
|
|
312
|
+
output = _allocate(plan.shape, result.dtype, room, zeros=blend)
|
|
313
|
+
if blend:
|
|
314
|
+
for axis, (part, by_range) in enumerate(zip(tile.read, weights)):
|
|
315
|
+
shape = [1] * result.ndim
|
|
316
|
+
shape[axis] = -1
|
|
317
|
+
result = result * by_range[part.start, part.stop].reshape(shape)
|
|
318
|
+
output[tile.read] = output[tile.read] + result
|
|
319
|
+
else:
|
|
320
|
+
output[tile.write] = result[tile.keep]
|
|
321
|
+
if isinstance(output, np.memmap):
|
|
322
|
+
output.flush()
|
|
323
|
+
return output
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def prepare_out(out: Any, shape: tuple[int, ...], dtype: Any) -> Any:
|
|
327
|
+
"""The array a result is written into, from what a caller passed as *out*.
|
|
328
|
+
|
|
329
|
+
*out* is anything that takes ``out[region] = values`` -- numpy, a zarr
|
|
330
|
+
array, an HDF5 dataset -- or a function ``(shape, dtype) -> array`` that
|
|
331
|
+
makes one, for a caller that cannot know the result's dtype until there
|
|
332
|
+
is one. Which kind of array is the caller's business; this only checks
|
|
333
|
+
that the shape is the result's.
|
|
334
|
+
"""
|
|
335
|
+
target = out(shape, dtype) if callable(out) else out
|
|
336
|
+
if tuple(target.shape) != tuple(shape):
|
|
337
|
+
raise ValueError(
|
|
338
|
+
f"out has shape {tuple(target.shape)}, but the result's is {tuple(shape)}"
|
|
339
|
+
)
|
|
340
|
+
return target
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _blend_weights(plan: TilePlan) -> list[dict[tuple[int, int], np.ndarray]]:
|
|
344
|
+
"""For each axis, the weight of each tile along it, by the tile's read range.
|
|
345
|
+
|
|
346
|
+
A tile's weight is 1 except across an overlap, where it ramps linearly
|
|
347
|
+
from 1 to 0 over the middle of the overlap, centred on the cut. The outer
|
|
348
|
+
part, nearest the edge of what the tile read, gets no weight: an op sees
|
|
349
|
+
that edge as the image's edge, so its result there is the least like the
|
|
350
|
+
untiled one. At a real image edge there is no overlap and no ramp. Each
|
|
351
|
+
weight is divided by the sum of all weights at that pixel, so the tiles'
|
|
352
|
+
weights add up to exactly 1 everywhere. Tiles are a grid, so a tile's
|
|
353
|
+
weight is the product of its weight along each axis.
|
|
354
|
+
"""
|
|
355
|
+
weights = []
|
|
356
|
+
for axis, size in enumerate(plan.shape):
|
|
357
|
+
parts = {
|
|
358
|
+
(t.read[axis].start, t.read[axis].stop): (
|
|
359
|
+
t.read[axis].start + t.keep[axis].start, # core start
|
|
360
|
+
t.read[axis].start + t.keep[axis].stop, # core stop
|
|
361
|
+
)
|
|
362
|
+
for t in plan.tiles
|
|
363
|
+
}
|
|
364
|
+
raw = {}
|
|
365
|
+
total = np.zeros(size, np.float64)
|
|
366
|
+
for (first, last), (start, stop) in parts.items():
|
|
367
|
+
x = np.arange(first, last) + 0.5
|
|
368
|
+
weight = np.ones(last - first)
|
|
369
|
+
if start > first: # overlap on the left: ramp up across the cut
|
|
370
|
+
side = start - first
|
|
371
|
+
ramp = (x - first - side / 2) / side
|
|
372
|
+
weight = np.minimum(weight, np.clip(ramp, 0, 1))
|
|
373
|
+
if last > stop: # and on the right: ramp down
|
|
374
|
+
side = last - stop
|
|
375
|
+
ramp = (last - x - side / 2) / side
|
|
376
|
+
weight = np.minimum(weight, np.clip(ramp, 0, 1))
|
|
377
|
+
raw[first, last] = weight
|
|
378
|
+
total[first:last] += weight
|
|
379
|
+
weights.append(
|
|
380
|
+
{
|
|
381
|
+
key: (weight / total[key[0] : key[1]]).astype(np.float32)
|
|
382
|
+
for key, weight in raw.items()
|
|
383
|
+
}
|
|
384
|
+
)
|
|
385
|
+
return weights
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _allocate(
|
|
389
|
+
shape: tuple[int, ...], dtype: Any, room: int, zeros: bool = False
|
|
390
|
+
) -> np.ndarray:
|
|
391
|
+
"""The whole output: in memory if it fits in *room*, on disk if not.
|
|
392
|
+
|
|
393
|
+
A new memmap file is zeros already; one in memory is only if *zeros*.
|
|
394
|
+
"""
|
|
395
|
+
if np.dtype(dtype).itemsize * int(np.prod(shape)) <= room:
|
|
396
|
+
return np.zeros(shape, dtype=dtype) if zeros else np.empty(shape, dtype=dtype)
|
|
397
|
+
folder = Path(tempfile.mkdtemp(prefix="oprunner-tiled-"))
|
|
398
|
+
return np.lib.format.open_memmap(
|
|
399
|
+
folder / "result.npy", mode="w+", dtype=dtype, shape=shape
|
|
400
|
+
)
|
oprunner/discovery.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Finding the ops in a collection.
|
|
2
|
+
|
|
3
|
+
Discovery works by importing op modules and reading their live signatures,
|
|
4
|
+
rather than by consulting a generated manifest that could drift. That is only
|
|
5
|
+
possible because ops keep heavy imports inside their function bodies -- which
|
|
6
|
+
means discovery doubles as enforcement of that rule. An op whose module scope
|
|
7
|
+
drags in tensorflow simply fails to load, and says so.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import importlib
|
|
13
|
+
import pkgutil
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
|
|
16
|
+
from opspec.op import OpSpec, is_op
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class LoadFailure:
|
|
21
|
+
"""An op module that could not be imported, and why."""
|
|
22
|
+
|
|
23
|
+
module: str
|
|
24
|
+
error: str
|
|
25
|
+
heavy_imports: tuple[str, ...]
|
|
26
|
+
|
|
27
|
+
def __str__(self) -> str:
|
|
28
|
+
lines = [f"Op module '{self.module}' could not be loaded: {self.error}"]
|
|
29
|
+
if self.heavy_imports:
|
|
30
|
+
lines.append(
|
|
31
|
+
" Module-scope imports found: "
|
|
32
|
+
+ ", ".join(self.heavy_imports)
|
|
33
|
+
+ "\n Move heavy imports inside the op function body -- ops are "
|
|
34
|
+
"discovered in a minimal environment."
|
|
35
|
+
)
|
|
36
|
+
return "\n".join(lines)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def discover(package: str = "skop.ops") -> tuple[list[OpSpec], list[LoadFailure]]:
|
|
40
|
+
"""Import every module in a collection and return the ops it declares.
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
The specs of every op found, and a failure record for each module
|
|
44
|
+
that could not be imported.
|
|
45
|
+
"""
|
|
46
|
+
# A collection that does not import at all is a bad argument rather than
|
|
47
|
+
# a bad op, so it raises instead of joining the failure list.
|
|
48
|
+
root = importlib.import_module(package)
|
|
49
|
+
specs: list[OpSpec] = []
|
|
50
|
+
failures: list[LoadFailure] = []
|
|
51
|
+
|
|
52
|
+
for module_name, module in _walk(package, root, failures):
|
|
53
|
+
for name in dir(module):
|
|
54
|
+
obj = getattr(module, name)
|
|
55
|
+
# NB: the name check keeps a re-exported op from being counted
|
|
56
|
+
# once per module that imports it -- which is what makes a
|
|
57
|
+
# namespace's __init__.py free to re-export its ops.
|
|
58
|
+
if is_op(obj) and obj.__module__ == module_name:
|
|
59
|
+
specs.append(OpSpec.from_op(obj))
|
|
60
|
+
|
|
61
|
+
specs.sort(key=lambda s: s.name)
|
|
62
|
+
return specs, failures
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _walk(package: str, module, failures: list[LoadFailure]):
|
|
66
|
+
"""Yield a collection and every module beneath it, depth first.
|
|
67
|
+
|
|
68
|
+
An op module may sit directly in the collection (``skop/ops/toy.py``),
|
|
69
|
+
inside a namespace (``skop/ops/segment/cellpose.py``), or be a package of
|
|
70
|
+
its own when one file is not enough (``skop/ops/segment/unseg/``). All
|
|
71
|
+
three are the same walk: import what is there, then descend into whatever
|
|
72
|
+
has submodules. Underscore-prefixed names are private helpers --
|
|
73
|
+
``_util.py``, ``_algorithm.py`` -- and are never imported.
|
|
74
|
+
"""
|
|
75
|
+
yield package, module
|
|
76
|
+
|
|
77
|
+
paths = getattr(module, "__path__", None)
|
|
78
|
+
if paths is None:
|
|
79
|
+
return
|
|
80
|
+
for info in pkgutil.iter_modules(paths):
|
|
81
|
+
if info.name.startswith("_"):
|
|
82
|
+
continue
|
|
83
|
+
name = f"{package}.{info.name}"
|
|
84
|
+
child = _import(name, failures)
|
|
85
|
+
if child is not None:
|
|
86
|
+
yield from _walk(name, child, failures)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _import(module_name: str, failures: list[LoadFailure]):
|
|
90
|
+
try:
|
|
91
|
+
return importlib.import_module(module_name)
|
|
92
|
+
except Exception as exc: # noqa: BLE001 -- one bad op must not hide the rest
|
|
93
|
+
failures.append(
|
|
94
|
+
LoadFailure(
|
|
95
|
+
module=module_name,
|
|
96
|
+
error=f"{type(exc).__name__}: {exc}",
|
|
97
|
+
heavy_imports=_module_scope_imports(module_name),
|
|
98
|
+
)
|
|
99
|
+
)
|
|
100
|
+
return None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _module_scope_imports(module_name: str) -> tuple[str, ...]:
|
|
104
|
+
"""Parse a module that would not import, to explain what it pulled in.
|
|
105
|
+
|
|
106
|
+
The import is the source of truth; this only produces the diagnostic, so
|
|
107
|
+
a best-effort answer beats a precise one.
|
|
108
|
+
"""
|
|
109
|
+
import ast
|
|
110
|
+
|
|
111
|
+
try:
|
|
112
|
+
spec_ = importlib.util.find_spec(module_name)
|
|
113
|
+
if spec_ is None or spec_.origin is None:
|
|
114
|
+
return ()
|
|
115
|
+
with open(spec_.origin, encoding="utf-8") as f:
|
|
116
|
+
tree = ast.parse(f.read())
|
|
117
|
+
except Exception: # noqa: BLE001 -- diagnostics must never raise
|
|
118
|
+
return ()
|
|
119
|
+
|
|
120
|
+
found = []
|
|
121
|
+
for node in tree.body:
|
|
122
|
+
if isinstance(node, ast.Import):
|
|
123
|
+
found.extend(f"{alias.name} (line {node.lineno})" for alias in node.names)
|
|
124
|
+
elif isinstance(node, ast.ImportFrom) and node.module:
|
|
125
|
+
found.append(f"{node.module} (line {node.lineno})")
|
|
126
|
+
return tuple(found)
|