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/runner.py ADDED
@@ -0,0 +1,901 @@
1
+ """The host-side half of oprunner: build environments and run ops in them.
2
+
3
+ The host never imports an op's dependencies. It imports the op module only to
4
+ read its signature -- which is cheap, because ops keep heavy imports inside
5
+ their function bodies -- and dispatches the actual call to a worker process
6
+ living in the op's declared environment.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import contextlib
12
+ import contextvars
13
+ import functools
14
+ import hashlib
15
+ import itertools
16
+ import json
17
+ import re
18
+ import sys
19
+ from collections.abc import Callable, Iterator
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+ from types import UnionType
23
+ from typing import TYPE_CHECKING, Any, Union, get_args, get_origin
24
+
25
+ import appose
26
+ import numpy as np
27
+
28
+ from opspec.op import FUNCTION, OpSpec, _strip
29
+ from opspec.runtime import bind_runner, bind_task, unbind_runner, unbind_task
30
+ from opspec.tiling import TilePlan
31
+ from opspec.types import Array
32
+
33
+ from . import _adapt, _codec, _tiling
34
+ from .host import CALL as _CALL
35
+ from .host import INIT as _INIT # noqa: F401 (kept for out-of-process hosts)
36
+ from .host import init_script as _init_script_for
37
+ from .host import is_checkout
38
+
39
+ if TYPE_CHECKING:
40
+ from typing import Self
41
+
42
+ # Note: _CALL and _INIT live in oprunner.host rather than here, because an
43
+ # out-of-process host needs them too and there must be exactly one copy of
44
+ # them. See docs/spec/fiji-front-end.md.
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class _Event:
49
+ """The shape of an Appose TaskEvent, for progress raised on the host."""
50
+
51
+ message: str | None = None
52
+ current: int | None = None
53
+ maximum: int | None = None
54
+ #: (m, n) when a tiled run starts its tile m of n. The op's own progress
55
+ #: for that tile follows, as ordinary events.
56
+ tile: tuple[int, int] | None = None
57
+
58
+
59
+ class _HostTask:
60
+ """Stands in for an Appose task while a workflow runs on the host.
61
+
62
+ A workflow has no worker and therefore no task, but everything watching an
63
+ op expects one: ``opspec.runtime.progress()`` looks for something to update, and a
64
+ GUI's Cancel button needs a handle to act on. This is that handle.
65
+ """
66
+
67
+ def __init__(self, on_progress: Callable[[Any], None] | None) -> None:
68
+ self._on_progress = on_progress
69
+ self.cancel_requested = False
70
+ self._child: Any = None
71
+
72
+ def update(
73
+ self,
74
+ message: str | None = None,
75
+ current: int | None = None,
76
+ maximum: int | None = None,
77
+ ) -> None:
78
+ self.relay(_Event(message, current, maximum))
79
+
80
+ def relay(self, event: Any) -> None:
81
+ """Pass an event on, whether it came from here or from a sub-op."""
82
+ if self._on_progress is not None:
83
+ self._on_progress(event)
84
+
85
+ def adopt(self, task: Any) -> None:
86
+ """Note the sub-op task now running, so a cancel can reach it."""
87
+ self._child = task
88
+ if self.cancel_requested:
89
+ task.cancel()
90
+
91
+ def cancel(self) -> None:
92
+ self.cancel_requested = True
93
+ # Nearly all of a workflow's time is spent inside a sub-op, so a
94
+ # cancel aimed at the workflow is useless unless it reaches that.
95
+ if self._child is not None:
96
+ self._child.cancel()
97
+
98
+
99
+ class _Ambient:
100
+ """The runner a workflow's own ``opspec.runtime.run`` calls should go through.
101
+
102
+ A workflow does not take a runner as a parameter, for the same reason an
103
+ op does not take a progress reporter as one (design 0001): it would make
104
+ calling the function directly awkward, and mode B has to stay a plain
105
+ Python call. So the runner is ambient, exactly as ``progress()`` is.
106
+ """
107
+
108
+ def __init__(
109
+ self, runner: Runner, task: _HostTask, tiler: _tiling.Tiler | None = None
110
+ ) -> None:
111
+ self._runner = runner
112
+ self._task = task
113
+ self._tiler = tiler
114
+
115
+ def run(self, fn: Callable, args: dict | None = None, **kwargs: Any) -> Any:
116
+ # A sub-op's progress is the workflow's progress: without this the
117
+ # panel sits at "running" for the four minutes SAM takes.
118
+ kwargs.setdefault("on_progress", self._task.relay)
119
+ kwargs.setdefault("on_start", self._task.adopt)
120
+ # The tiling the workflow's caller chose applies to the ops it calls,
121
+ # unless the workflow chose for one itself.
122
+ if self._tiler is not None and not {"tiler", "memory"} & kwargs.keys():
123
+ kwargs["tiler"] = self._tiler
124
+ return self._runner.run(fn, args, **kwargs)
125
+
126
+
127
+ _current: contextvars.ContextVar[_Ambient | None] = contextvars.ContextVar(
128
+ "oprunner", default=None
129
+ )
130
+
131
+
132
+ def _default_root() -> Path:
133
+ """The directory holding the ``oprunner`` package: a checkout's
134
+ ``oprunner/src``, or site-packages."""
135
+ return Path(__file__).resolve().parent.parent
136
+
137
+
138
+ def _default_envs_dir(root: Path) -> Path | None:
139
+ """Environments asked for by ID alone, with no op to find them beside.
140
+
141
+ An op's environment is found beside the op's own files (``_env_for``), so
142
+ this is only for calls such as ``ensure_environment("cupy")``. In a
143
+ scikit-ops checkout it is the repository's ``envs/``: oprunner sits in
144
+ ``oprunner/src``, two folders below. Elsewhere there is none.
145
+
146
+ A stopgap: once collections say where their environments are, a runner
147
+ needs no default.
148
+ """
149
+ checkout = root.parent.parent / "envs"
150
+ return checkout if checkout.is_dir() else None
151
+
152
+
153
+ class Runner:
154
+ """Builds environments, keeps workers warm, and dispatches op calls."""
155
+
156
+ def __init__(
157
+ self,
158
+ root: Path | str | None = None,
159
+ envs_dir: Path | str | None = None,
160
+ debug: bool = False,
161
+ ) -> None:
162
+ self.root = Path(root).resolve() if root else _default_root()
163
+ self.envs_dir = (
164
+ Path(envs_dir).resolve() if envs_dir else _default_envs_dir(self.root)
165
+ )
166
+ self.debug = debug
167
+ self._services: dict[tuple, Any] = {}
168
+ self._envs: dict[tuple, Any] = {}
169
+ self._build_progress: list[Callable[[str, int, int], None]] = []
170
+ self._build_output: list[Callable[[str], None]] = []
171
+ self._build_error: list[Callable[[str], None]] = []
172
+
173
+ # -- build reporting -------------------------------------------------
174
+
175
+ def subscribe_build_progress(
176
+ self, subscriber: Callable[[str, int, int], None]
177
+ ) -> None:
178
+ """Hear about environment build progress, as (title, current, maximum).
179
+
180
+ Building an environment is by far the slowest thing a first run does
181
+ -- minutes, for a TensorFlow or PyTorch stack -- and it happens inside
182
+ ``run``, with nothing else to show for it. Anything with a progress
183
+ bar wants these.
184
+
185
+ Titles come from Appose's PixiInstallMonitor, and name the phase:
186
+ "Solving", "Installing conda packages", "Downloading PyPI packages",
187
+ "Installing PyPI packages", "Done". Note that subscribing here is
188
+ what switches the monitor on -- it runs pixi under ``-vv`` to read
189
+ its phase transitions, so without a progress subscriber a build
190
+ reports only its final summary line.
191
+ """
192
+ self._build_progress.append(subscriber)
193
+
194
+ def subscribe_build_output(self, subscriber: Callable[[str], None]) -> None:
195
+ """Hear the build tool's standard output, in raw chunks."""
196
+ self._build_output.append(subscriber)
197
+
198
+ def subscribe_build_error(self, subscriber: Callable[[str], None]) -> None:
199
+ """Hear the build tool's standard error, in raw chunks.
200
+
201
+ Note: this is the stderr *stream*, not a failure report. Pixi writes
202
+ its ordinary status there, success message included, and once a
203
+ progress subscriber has turned on ``-vv`` it writes its whole debug
204
+ log there too. A build that actually fails raises from ``run``.
205
+ """
206
+ self._build_error.append(subscriber)
207
+
208
+ # -- environments ----------------------------------------------------
209
+
210
+ def env_config(self, env_id: str) -> Path:
211
+ if self.envs_dir is None:
212
+ raise FileNotFoundError(
213
+ f"No environment '{env_id}': this runner has no envs_dir. "
214
+ "Pass Runner(envs_dir=...), or ask about an op with env_for(op)."
215
+ )
216
+ config = self.envs_dir / env_id / "pixi.toml"
217
+ if not config.exists():
218
+ known = ", ".join(sorted(self.env_ids())) or "none"
219
+ raise FileNotFoundError(
220
+ f"No environment '{env_id}' at {config}. Known environments: {known}"
221
+ )
222
+ return config
223
+
224
+ def env_ids(self) -> Iterator[str]:
225
+ if self.envs_dir is None or not self.envs_dir.is_dir():
226
+ return
227
+ for child in sorted(self.envs_dir.iterdir()):
228
+ if (child / "pixi.toml").exists():
229
+ yield child.name
230
+
231
+ def env_dir(self, env_id: str) -> Path:
232
+ """Where Appose keeps the built environment for *env_id*.
233
+
234
+ ``<package>--<env_id>``, as ``environment`` builds it. The
235
+ directory need not exist; that is what "missing" means below.
236
+ """
237
+ return self._own_env(env_id).folder
238
+
239
+ def environment_status(self, env_id: str) -> str:
240
+ """Whether the built environment matches its definition.
241
+
242
+ One of ``"ready"``, ``"stale"`` or ``"missing"``. Answered from
243
+ the two files, without building anything, so it costs nothing to ask.
244
+
245
+ Appose records the full text of the pixi.toml it built from, in
246
+ ``appose.json`` beside the environment. Comparing that against the
247
+ definition in ``envs/<env_id>/pixi.toml`` says whether the environment
248
+ anyone is about to run in is the one currently described.
249
+
250
+ Worth having because the failure it catches is silent. An environment
251
+ built before a fix stays built, keeps running, and reports nothing --
252
+ which is how a stack can be missing CUDA for months while every run
253
+ appears to succeed.
254
+ """
255
+ config = self.env_config(env_id)
256
+ record = self.env_dir(env_id) / "appose.json"
257
+ if not record.exists():
258
+ return "missing"
259
+ try:
260
+ built = json.loads(record.read_text()).get("content", "")
261
+ except (OSError, ValueError):
262
+ return "stale"
263
+ return "ready" if built.strip() == config.read_text().strip() else "stale"
264
+
265
+ def ensure_environment(
266
+ self,
267
+ env_id: str,
268
+ variant: str | None = None,
269
+ report: Callable[[str], None] = print,
270
+ ) -> Any:
271
+ """Build *env_id* if it is missing or out of date, saying which.
272
+
273
+ ``environment`` builds or reuses and tells you neither, so a cell that
274
+ sits silent for ten minutes looks the same as one that did nothing.
275
+ This says what it is about to do first, and subscribes to the build
276
+ output for the duration if nothing else has, so a rebuild is visible
277
+ as it happens rather than only in the wall clock.
278
+
279
+ Args:
280
+ env_id: The environment to ensure, e.g. ``"stardist-tf"``.
281
+ variant: A named pixi sub-environment, or None for the default.
282
+ report: Where the status lines go. ``print`` suits a notebook.
283
+
284
+ Returns:
285
+ The Appose environment, as ``environment`` does.
286
+ """
287
+ status = self.environment_status(env_id)
288
+ report(f"{env_id}: {status}")
289
+ if status == "ready":
290
+ return self.environment(env_id, variant)
291
+
292
+ report(
293
+ f"{env_id}: building from {self.env_config(env_id)} -- "
294
+ f"this takes minutes and gigabytes on a first build"
295
+ )
296
+ added = []
297
+ if not self._build_output:
298
+ self._build_output.append(report)
299
+ added.append(self._build_output)
300
+ if not self._build_error:
301
+ self._build_error.append(report)
302
+ added.append(self._build_error)
303
+ try:
304
+ env = self.environment(env_id, variant)
305
+ finally:
306
+ for subscribers in added:
307
+ subscribers.pop()
308
+ report(f"{env_id}: ready")
309
+ return env
310
+
311
+ def environment(self, env_id: str, variant: str | None = None) -> Any:
312
+ """Build (or reuse) the Appose environment for an env ID.
313
+
314
+ Appose keys environments by name in its shared environments
315
+ directory, so several ops declaring the same env ID land on the same
316
+ installation, and editing the pixi.toml triggers a rebuild.
317
+ """
318
+ return self._build(self._own_env(env_id), variant)
319
+
320
+ def env_for(self, op: Callable) -> Env:
321
+ """The environment *op* runs in: the file that defines it, and where
322
+ it is built. Nothing is built by asking.
323
+ """
324
+ spec = OpSpec.from_op(op)
325
+ if spec.env is None:
326
+ raise ValueError(f"Op {spec.name} has no environment: it runs here")
327
+ return self._env_for(spec.env, spec.module)
328
+
329
+ def _env_for(self, env_id: str, module: str) -> Env:
330
+ """The environment an op in *module* means by *env_id*.
331
+
332
+ An ``envs/<env_id>/pixi.toml`` beside the op's own files comes first:
333
+ in its folder, or any folder above it. So a collection of ops outside
334
+ scikit-ops can bring its own environments, even ones named like
335
+ scikit-ops' -- each is built, and run, as itself. Failing that, this
336
+ runner's ``envs_dir``.
337
+ """
338
+ found = getattr(sys.modules.get(module), "__file__", None)
339
+ if found is not None:
340
+ for folder in Path(found).resolve().parents:
341
+ config = folder / "envs" / env_id / "pixi.toml"
342
+ if config.exists():
343
+ return Env(env_id, config, _package_name(module, folder))
344
+ return self._own_env(env_id)
345
+
346
+ def _own_env(self, env_id: str) -> Env:
347
+ """One of this runner's own environments, from its ``envs_dir``."""
348
+ config = self.env_config(env_id)
349
+ return Env(env_id, config, _package_name(__name__, self.envs_dir.parent))
350
+
351
+ def _build(self, env: Env, variant: str | None = None) -> Any:
352
+ """Build (or reuse) one environment."""
353
+ key = (env.config, variant)
354
+ if key in self._envs:
355
+ return self._envs[key]
356
+
357
+ builder = appose.pixi(env.config).name(env.name)
358
+ for progress_subscriber in self._build_progress:
359
+ builder = builder.subscribe_progress(progress_subscriber)
360
+ for output_subscriber in self._build_output:
361
+ builder = builder.subscribe_output(output_subscriber)
362
+ for error_subscriber in self._build_error:
363
+ builder = builder.subscribe_error(error_subscriber)
364
+ if self.debug:
365
+ builder = builder.log_debug()
366
+ built = builder.build()
367
+
368
+ if variant is not None:
369
+ # Named pixi sub-environments (features) require appose >= 0.12.
370
+ if not hasattr(built, "activate"):
371
+ raise RuntimeError(
372
+ f"Environment variant '{variant}' requires appose >= 0.12; "
373
+ f"installed appose has no Environment.activate()."
374
+ )
375
+ built = built.activate(variant)
376
+
377
+ self._envs[key] = built
378
+ return built
379
+
380
+ def _init_script(self, env: Env) -> str:
381
+ script = _init_script_for(self.root)
382
+ extra = env.config.parent / "init.py"
383
+ if extra.exists():
384
+ script = f"{script}\n{extra.read_text(encoding='utf-8')}"
385
+ return script
386
+
387
+ def service(self, spec: OpSpec, variant: str | None = None) -> Any:
388
+ """Get the worker serving this op, starting one if needed.
389
+
390
+ Ops sharing an environment share a worker, unless one of them asks
391
+ to be exclusive.
392
+ """
393
+ env = self._env_for(spec.env, spec.module)
394
+ key = (spec.env, env.config, variant, spec.name if spec.exclusive else None)
395
+ service = self._services.get(key)
396
+ if service is not None:
397
+ return service
398
+
399
+ built = self._build(env, variant)
400
+ service = built.python().init(self._init_script(env))
401
+ if self.debug:
402
+ service.debug(lambda line: print(f"[{spec.env}] {line}"))
403
+ service.start()
404
+ self._services[key] = service
405
+ return service
406
+
407
+ # -- running ---------------------------------------------------------
408
+
409
+ def run(
410
+ self,
411
+ fn: Callable,
412
+ args: dict | None = None,
413
+ *,
414
+ variant: str | None = None,
415
+ axes: dict[str, str] | None = None,
416
+ plans: dict[str, _adapt.AdaptationPlan] | None = None,
417
+ position: dict[str, int] | None = None,
418
+ on_progress: Callable[[Any], None] | None = None,
419
+ on_start: Callable[[Any], None] | None = None,
420
+ memory: int | str | None = None,
421
+ tiler: _tiling.Tiler | None = None,
422
+ out: Any = None,
423
+ **kwargs: Any,
424
+ ) -> Any:
425
+ """Run an op in its environment and return its result.
426
+
427
+ Args:
428
+ fn: The op function, as decorated with ``@op``.
429
+ args: Op arguments, as a dict. Merged with ``**kwargs``, which is
430
+ the more convenient form when no argument name collides with
431
+ this method's own parameters.
432
+ variant: Optional named pixi sub-environment (e.g. ``"cuda"``).
433
+ axes: What each array argument actually is, as ``{"image":
434
+ list("zyx")}`` or ``{"image": ("pln", "row", "col")}``. Naming
435
+ them lets oprunner fit them to what the op consumes -- transposing,
436
+ or iterating a 2-D op over a stack. An axis label is any
437
+ string, so ``("lifetime", "y", "x")`` works as well as the
438
+ canonical letters, and known synonyms resolve to them.
439
+ Unnamed arrays are passed through untouched.
440
+ plans: Explicit ``AdaptationPlan``s, from ``opspec.plan.plan``, for
441
+ callers making the per-axis decisions themselves. Overrides
442
+ ``axes`` for the parameters it names. The plan oprunner builds on
443
+ its own never discards data, so supply one whenever that is
444
+ what you actually want.
445
+ position: Current position along each axis, used only when a
446
+ supplied plan indexes down to a single plane.
447
+ on_progress: Called with each Appose TaskEvent as it arrives.
448
+ on_start: Called with the Appose Task when it is submitted. This
449
+ can be used to get a reference to the running task, then the
450
+ reference can be used to monitor or cancel the task.
451
+ memory: A memory budget for the op, as bytes or a size such as
452
+ ``"1G"``. An op declaring tiling hints (``@op(tile=...,
453
+ peak_memory=...)``) whose input would need more is run tile by
454
+ tile, each within the budget; see ``oprunner._tiling``. Left out,
455
+ the budget is 85% of the memory available right now, cgroup
456
+ limits included (``oprunner._tiling.default_budget``); ``"off"``
457
+ never tiles. An op declaring no hints always runs whole. A
458
+ shortcut for ``tiler=Tiler(memory)``.
459
+ tiler: The caller's tiling choices -- budget, overlap, tile size
460
+ -- as a ``oprunner.Tiler``; it takes precedence over ``memory``.
461
+ ``Tiler.off()`` never tiles. For a workflow, it applies to
462
+ the ops the workflow runs.
463
+ out: Where an op's single array result is written, tiled or not:
464
+ an array that takes ``out[region] = values`` (numpy, zarr,
465
+ HDF5), or a function ``(shape, dtype) -> array`` that makes
466
+ one once the result's dtype is known. Returned in place of a
467
+ new array. Left out, a tiled result too big for memory goes
468
+ to a temporary ``.npy`` memmap.
469
+ """
470
+ spec = OpSpec.from_op(fn)
471
+ call_args = dict(args or {})
472
+ call_args.update(kwargs)
473
+ _validate(spec, call_args)
474
+
475
+ if tiler is None:
476
+ tiler = _tiling.Tiler.off() if memory == "off" else _tiling.Tiler(memory)
477
+ plan = tiler.plan(spec, call_args)
478
+ if plan is not None and plan.calls > 1:
479
+ if axes or any(_adapts(p) for p in (plans or {}).values()):
480
+ raise NotImplementedError(
481
+ f"Op {spec.name}: tiling and axis adaptation in one call "
482
+ "are not supported yet; give one or the other"
483
+ )
484
+ # All the inputs in spec.tile are tiled the same way; one left out
485
+ # of the call -- an optional mask -- stays None.
486
+ inputs = {name: call_args.get(name) for name in spec.tile}
487
+ started = itertools.count(1)
488
+
489
+ def one_tile(pieces: dict[str, Any]) -> Any:
490
+ number = next(started)
491
+ if on_progress is not None:
492
+ on_progress(
493
+ _Event(
494
+ f"Tile {number} of {plan.calls}",
495
+ number - 1,
496
+ plan.calls,
497
+ tile=(number, plan.calls),
498
+ )
499
+ )
500
+ return self.run(
501
+ fn,
502
+ {**call_args, **pieces},
503
+ tiler=_tiling.Tiler.off(), # Already cut to fit.
504
+ variant=variant,
505
+ on_progress=on_progress,
506
+ on_start=on_start,
507
+ )
508
+
509
+ # The whole result is in RAM, whatever device the op is on:
510
+ # a GPU op's budget says nothing about how much RAM is free.
511
+ room = (
512
+ _tiling.default_budget() if spec.peak_memory.device == "gpu" else None
513
+ )
514
+ return _tiling.run_tiles(one_tile, inputs, plan, out, room, spec.merge)
515
+
516
+ call_args = _to_declared(spec, call_args)
517
+
518
+ if spec.is_workflow:
519
+ # No environment to dispatch to, and nothing to encode: a workflow
520
+ # runs here, and the ops it calls each cross the boundary
521
+ # themselves. Axis adaptation is skipped for the same reason --
522
+ # the sub-ops adapt their own arrays.
523
+ return _into(
524
+ out, self._run_here(fn, call_args, on_progress, on_start, tiler)
525
+ )
526
+
527
+ adaptations = _adaptations(fn, call_args, axes, plans, position)
528
+
529
+ service = self.service(spec, variant)
530
+
531
+ refs: list = []
532
+ # Buffers the caller owns and expects to see written to: for computer
533
+ # and inplace ops we must copy results back out of shared memory.
534
+ buffers: dict[str, tuple[np.ndarray, Any]] = {}
535
+ try:
536
+ encoded = {}
537
+ by_name = {p.name: p for p in spec.params}
538
+ for name, value in call_args.items():
539
+ param = by_name[name]
540
+ if param.direction is not None and isinstance(value, np.ndarray):
541
+ nda = _codec._to_ndarray(value, refs)
542
+ buffers[name] = (value, nda)
543
+ encoded[name] = nda
544
+ else:
545
+ encoded[name] = _codec.encode(value, refs)
546
+
547
+ task = service.task(
548
+ _CALL,
549
+ {
550
+ "module": spec.module,
551
+ "function": spec.function,
552
+ "kwargs": encoded,
553
+ "plans": [plan.to_dict() for plan in adaptations.values()],
554
+ "origin": _origin(spec.module),
555
+ },
556
+ queue="main" if spec.main_thread else None,
557
+ )
558
+ if on_progress is not None:
559
+ task.listen(on_progress)
560
+ if on_start is not None:
561
+ on_start(task)
562
+ task.wait_for()
563
+
564
+ for caller_array, nda in buffers.values():
565
+ caller_array[...] = nda.ndarray()
566
+
567
+ out_refs: list = []
568
+ try:
569
+ outputs = _codec.decode(dict(task.outputs), out_refs)
570
+ outputs = _codec.copy_out(outputs)
571
+ finally:
572
+ # The host owns cleanup of shared memory, including blocks
573
+ # the worker allocated for results.
574
+ _codec.release(out_refs, unlink=True)
575
+
576
+ return _into(out, _unpack(spec, outputs, buffers))
577
+ finally:
578
+ _codec.release(refs, unlink=True)
579
+
580
+ def _run_here(
581
+ self,
582
+ fn: Callable,
583
+ call_args: dict,
584
+ on_progress: Callable[[Any], None] | None,
585
+ on_start: Callable[[Any], None] | None,
586
+ tiler: _tiling.Tiler | None = None,
587
+ ) -> Any:
588
+ """Call a workflow in this process, with this runner made ambient."""
589
+ task = _HostTask(on_progress)
590
+ if on_start is not None:
591
+ on_start(task)
592
+ reporting = bind_task(task)
593
+ here = _Ambient(self, task, tiler)
594
+ ambient = _current.set(here)
595
+ # opspec.runtime.run goes through this runner too.
596
+ sub_ops = bind_runner(here)
597
+ try:
598
+ return fn(**call_args)
599
+ finally:
600
+ unbind_runner(sub_ops)
601
+ _current.reset(ambient)
602
+ unbind_task(reporting)
603
+
604
+ #: Run in a worker to hand GPU memory back. Torch frees tensors into its
605
+ #: own cache, not to the driver; cupy does the same. TensorFlow keeps
606
+ #: what it took either way -- see docs/design/0019.
607
+ _RELEASE = """
608
+ import gc
609
+ gc.collect()
610
+ try:
611
+ import torch
612
+ torch.cuda.empty_cache()
613
+ except Exception:
614
+ pass
615
+ try:
616
+ import cupy
617
+ cupy.get_default_memory_pool().free_all_blocks()
618
+ except Exception:
619
+ pass
620
+ task.outputs['released'] = True
621
+ """
622
+
623
+ def release(self, env: str | None = None, close: bool = False) -> None:
624
+ """Give back GPU memory in live workers.
625
+
626
+ *env* names one environment, or None for all of them. By default the
627
+ worker stays up and only returns what it had cached; what an op still
628
+ references stays held. ``close=True`` shuts the worker down instead,
629
+ which is the only thing that frees a TensorFlow environment.
630
+ """
631
+ for key, service in list(self._services.items()):
632
+ if env is not None and key[0] != env:
633
+ continue
634
+ with contextlib.suppress(Exception):
635
+ if close:
636
+ service.close()
637
+ del self._services[key]
638
+ else:
639
+ service.task(self._RELEASE).wait_for()
640
+
641
+ def close(self) -> None:
642
+ """Shut down every worker this runner started."""
643
+ for service in self._services.values():
644
+ # A worker that already died is still closed, as far as we care.
645
+ with contextlib.suppress(Exception):
646
+ service.close()
647
+ self._services.clear()
648
+
649
+ def __enter__(self) -> Self:
650
+ return self
651
+
652
+ def __exit__(self, exc_type, exc_value, exc_tb) -> None:
653
+ self.close()
654
+
655
+
656
+ def _validate(spec: OpSpec, args: dict) -> None:
657
+ known = {p.name for p in spec.params}
658
+ unknown = set(args) - known
659
+ if unknown:
660
+ raise TypeError(
661
+ f"Op {spec.name} has no parameter(s): {', '.join(sorted(unknown))}"
662
+ )
663
+ missing = [p.name for p in spec.params if p.required and p.name not in args]
664
+ if missing:
665
+ raise TypeError(
666
+ f"Op {spec.name} is missing required argument(s): {', '.join(missing)}"
667
+ )
668
+
669
+
670
+ def _adapts(plan: _adapt.AdaptationPlan) -> bool:
671
+ """Whether a plan changes anything: slices, iterates or reorders.
672
+
673
+ A front end hands over a plan for every input whose op declares axes,
674
+ including the many that come out "as is"; only the rest stand in the way
675
+ of tiling.
676
+ """
677
+ identity = tuple(range(len(plan.transpose)))
678
+ return bool(plan.iterate or plan.select) or tuple(plan.transpose) != identity
679
+
680
+
681
+ def _into(out: Any, result: Any) -> Any:
682
+ """*result*, written into *out* when the caller gave one."""
683
+ if out is None:
684
+ return result
685
+ if isinstance(result, tuple):
686
+ raise TypeError(
687
+ f"out takes a single array, and this op returned {len(result)} values"
688
+ )
689
+ array = np.asarray(result)
690
+ target = _tiling.prepare_out(out, array.shape, array.dtype)
691
+ target[...] = array
692
+ return target
693
+
694
+
695
+ def tile_plan(
696
+ spec: OpSpec, args: dict, memory: int | str | None = None
697
+ ) -> TilePlan | None:
698
+ """How ``Runner.run(..., memory=memory)`` would cut this call.
699
+
700
+ Kept for front ends that predate the Tiler: ``Tiler(memory).plan``.
701
+ """
702
+ return _tiling.Tiler(memory).plan(spec, args)
703
+
704
+
705
+ def _to_declared(spec: OpSpec, args: dict) -> dict:
706
+ """If a param isn't a numpy array but the op wants one, convert it.
707
+
708
+ The whole array is read into memory (see docs/design/0017).
709
+ """
710
+ converted = dict(args)
711
+ for param in spec.params:
712
+ value = args.get(param.name)
713
+ if isinstance(value, np.ndarray) or not isinstance(value, Array):
714
+ continue
715
+ if not _wants_numpy(param.type, value):
716
+ continue
717
+ if param.direction is not None:
718
+ raise TypeError(
719
+ f"Op {spec.name}: {param.name} is written to, so it must be "
720
+ f"numpy, not {type(value).__name__}"
721
+ )
722
+ converted[param.name] = np.asarray(value)
723
+ return converted
724
+
725
+
726
+ def _wants_numpy(annotation: Any, value: Any) -> bool:
727
+ """Does the annotation need numpy? Not if it also accepts *value* as is."""
728
+ if get_origin(annotation) in (Union, UnionType):
729
+ members = [_strip(a) for a in get_args(annotation)]
730
+ else:
731
+ members = [annotation]
732
+ members = [get_origin(m) or m for m in members] # NDArray[...] -> ndarray
733
+ if np.ndarray not in members:
734
+ return False
735
+ return not any(isinstance(m, type) and isinstance(value, m) for m in members)
736
+
737
+
738
+ def _adaptations(
739
+ fn: Callable,
740
+ args: dict,
741
+ axes: dict[str, str] | None,
742
+ plans: dict[str, _adapt.AdaptationPlan] | None,
743
+ position: dict[str, int] | None,
744
+ ) -> dict[str, _adapt.AdaptationPlan]:
745
+ """Settle on one plan per parameter whose array was given axis labels.
746
+
747
+ A parameter goes unadapted unless someone said something about it. That
748
+ keeps naming axes opt-in: an existing caller passing a bare array gets
749
+ exactly the behavior it got before.
750
+ """
751
+ chosen = dict(plans or {})
752
+ for name, labels in (axes or {}).items():
753
+ if name in chosen:
754
+ continue
755
+ chosen[name] = _adapt.plan(fn, name, args[name], labels, position)
756
+ return chosen
757
+
758
+
759
+ def _unpack(spec: OpSpec, outputs: dict, buffers: dict) -> Any:
760
+ names = tuple(o.name for o in spec.outputs)
761
+ if not names:
762
+ return None
763
+ if spec.form != FUNCTION:
764
+ # Results landed in the caller's own buffers.
765
+ owned = [buffers[name][0] for name in names if name in buffers]
766
+ if not owned:
767
+ return None
768
+ return owned[0] if len(owned) == 1 else tuple(owned)
769
+ if names == ("result",):
770
+ return outputs.get("result")
771
+ values = [outputs.get(name) for name in names]
772
+ factory = spec.return_type
773
+ if getattr(factory, "_fields", None) == tuple(names):
774
+ return factory(*values)
775
+ return tuple(values)
776
+
777
+
778
+ _default_runner: Runner | None = None
779
+
780
+
781
+ def default_runner() -> Runner:
782
+ """A process-wide Runner, for callers that do not want to manage one."""
783
+ global _default_runner
784
+ if _default_runner is None:
785
+ _default_runner = Runner()
786
+ return _default_runner
787
+
788
+
789
+ @dataclass(frozen=True)
790
+ class Env:
791
+ """An environment an op asked for: its ID, and the file that defines it.
792
+
793
+ ``Runner.env_for(op)`` gives one; ``name`` and ``folder`` say what it is
794
+ built as, and where.
795
+ """
796
+
797
+ id: str
798
+ config: Path
799
+ #: Whose environment it is: the op's package, e.g. ``tnia-ops``.
800
+ package: str
801
+
802
+ @property
803
+ def name(self) -> str:
804
+ """What Appose builds it as: ``<package>--<id>``.
805
+
806
+ ``scikit-ops--decon`` and ``tnia-ops--decon`` are two environments,
807
+ though both are ``decon``: two collections' authors need not know of
808
+ each other for their environments to stay apart.
809
+ """
810
+ return f"{self.package}--{self.id}"
811
+
812
+ @property
813
+ def folder(self) -> Path:
814
+ """Where Appose builds it. It need not exist yet."""
815
+ try:
816
+ from appose.util.filepath import appose_envs_dir
817
+ except ImportError: # older appose kept it next door
818
+ from appose.util.environment import appose_envs_dir
819
+
820
+ return Path(appose_envs_dir()) / self.name
821
+
822
+
823
+ def _package_name(module: str, root: Path) -> str:
824
+ """Whose environments these are, for naming them: a package's name.
825
+
826
+ From the ``pyproject.toml`` beside ``envs/``, for a checkout; else from
827
+ the installed distribution *module* belongs to; else, for a plain folder,
828
+ its name and a short hash of where it is.
829
+ """
830
+ project = root / "pyproject.toml"
831
+ if project.exists():
832
+ found = _project_name(project.read_text(encoding="utf-8"))
833
+ if found:
834
+ return _normalized(found)
835
+ for name in _distributions().get(module.split(".")[0], []):
836
+ return _normalized(name)
837
+ where = hashlib.sha1(str(root.resolve()).encode()).hexdigest()[:6]
838
+ return f"{root.name}-{where}"
839
+
840
+
841
+ def _project_name(text: str) -> str | None:
842
+ """``[project] name`` from a pyproject.toml's text."""
843
+ try:
844
+ import tomllib
845
+ except ImportError: # Python 3.10
846
+ section = text.split("[project]", 1)[-1]
847
+ found = re.search(r'^name\s*=\s*"([^"]+)"', section, re.MULTILINE)
848
+ return found.group(1) if found else None
849
+ return tomllib.loads(text).get("project", {}).get("name")
850
+
851
+
852
+ def _normalized(name: str) -> str:
853
+ """A package name as PyPI compares them: tnia_ops and Tnia.Ops are tnia-ops."""
854
+ return re.sub(r"[-_.]+", "-", name).lower()
855
+
856
+
857
+ @functools.cache
858
+ def _distributions() -> dict:
859
+ """Top-level import name to distribution names. Slow to work out, once."""
860
+ import importlib.metadata
861
+
862
+ return importlib.metadata.packages_distributions()
863
+
864
+
865
+ def _origin(module: str) -> dict | None:
866
+ """Where a worker can import *module* from, as the host found it.
867
+
868
+ ``{"root": folder}``, the folder to put on the path; None when the host
869
+ has no file for it, or the op is in a script run directly (``__main__``),
870
+ which a worker cannot import.
871
+ """
872
+ found = getattr(sys.modules.get(module), "__file__", None)
873
+ if found is None:
874
+ return None
875
+ if module == "__main__":
876
+ return None
877
+ path = Path(found).resolve()
878
+ # pkg/sub/mod.py is pkg.sub.mod: up one folder per dotted part, and one
879
+ # more for a package's __init__.py.
880
+ depth = module.count(".") + (path.name == "__init__.py")
881
+ root = path.parents[depth]
882
+ origin: dict = {"root": str(root)}
883
+ if not is_checkout(root):
884
+ # Installed: the worker's environment should have its own copy, and
885
+ # the host's site-packages holds packages built for the host's Python,
886
+ # so the worker only falls back to it, last on its path.
887
+ origin["append"] = True
888
+ return origin
889
+
890
+
891
+ def run(fn: Callable, args: dict | None = None, **kwargs: Any) -> Any:
892
+ """Run an op via the default Runner.
893
+
894
+ Inside a workflow this goes through *that* runner instead, so a sub-op
895
+ reuses the warm workers the workflow was started with -- and so a panel's
896
+ progress bar and Cancel button reach it.
897
+ """
898
+ ambient = _current.get()
899
+ if ambient is not None:
900
+ return ambient.run(fn, args, **kwargs)
901
+ return default_runner().run(fn, args, **kwargs)