Skip to content

Commit 64b5e76

Browse files
authored
Merge pull request #10 from OpenHCSDev/feat/array-operations-for-memory
ArrayOperations.for_memory(): one registered leaf per memory type, holding the primitives that differ (0.4.0)
2 parents 31632d8 + 6f6f907 commit 64b5e76

9 files changed

Lines changed: 339 additions & 40 deletions

‎ADDING_NEW_FRAMEWORKS.md‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,17 @@ own framework registry.
66

77
## 1. Define typed leaves
88

9-
Add an `ArrayOperations` bundle in
10-
`src/arraybridge/array_operations.py`. It must provide four ordinary callables:
9+
Add an `ArrayOperations` leaf in `src/arraybridge/array_operations.py`: a
10+
subclass declaring `memory_type = "<value>"`. It registers itself, and
11+
`ArrayOperations.for_memory(MemoryType.<MEMBER>)` returns it. It must provide:
1112

1213
- project an array to NumPy;
1314
- create an array from NumPy on the requested framework-local device;
1415
- stack prepared 2D arrays into one 3D array;
15-
- apply the framework's dtype-scaling semantics.
16+
- apply the framework's dtype-scaling semantics;
17+
- an override of each namespace primitive (`max`, `mean`, `assign`,
18+
`linspace`, ...) whose library call or numeric rule differs from the
19+
NumPy-compatible default.
1620

1721
Define device, stream, DLPack, cleanup, and OOM leaves in
1822
`src/arraybridge/types.py`. Use the no-op defaults in `FrameworkRuntime` only
@@ -27,8 +31,7 @@ Add one `MemoryType` member carrying:
2731
2. its display name and module aliases;
2832
3. whether it is GPU-backed;
2933
4. any environment defaults that must be set before first import;
30-
5. its `FrameworkRuntime` leaves;
31-
6. its `ArrayOperations` bundle.
34+
5. its `FrameworkRuntime` leaves.
3235

3336
The converter classes, target conversion methods, compatibility operation view,
3437
dtype-scaling view, cleanup adapters, and framework decorator are generated

‎CONTRIBUTING.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -404,8 +404,8 @@ GitHub Actions will automatically:
404404

405405
To add support for a new framework:
406406

407-
1. Add typed array-operation leaves in `array_operations.py`.
408-
2. Add one `MemoryType` declaration carrying those operations and its runtime leaves.
407+
1. Add one `ArrayOperations` leaf in `array_operations.py` declaring its `memory_type`.
408+
2. Add one `MemoryType` declaration carrying its runtime leaves.
409409
3. Add detection, conversion-pair, stack, cross-device, and optional-dependency tests.
410410
4. Update the extension and reference documentation.
411411

‎README.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,3 +85,27 @@ provide native changed-shape reshape or broadcasting, so those requests raise
8585
`NotImplementedError`. Its native ones allocation supports one to three
8686
dimensions and its supported integer/float32 dtypes; boolean allocation is
8787
explicitly unsupported. Existing conversion and disk boundaries remain separate.
88+
89+
### Writing an operation once for every framework
90+
91+
`ArrayOperations.for_memory(memory_type)` returns that framework's operations
92+
leaf: one registered subclass per `MemoryType`, holding only the primitives its
93+
library does differently (`max`, `min`, `mean`, `sum`, `astype`,
94+
`prepend_axis`, `linspace`, `ones`, `assign`, `outer`, `floor`, `accepts`).
95+
Code written against the leaf runs natively in each framework:
96+
97+
```python
98+
from arraybridge import MemoryType
99+
from arraybridge.array_operations import ArrayOperations
100+
101+
102+
def max_projection(ops, stack):
103+
return ops.prepend_axis(ops.max(stack, 0))
104+
105+
106+
ops = ArrayOperations.for_memory(MemoryType.TORCH)
107+
```
108+
109+
`ops.module` is the framework, imported on first use. Each leaf keeps its
110+
library's numeric rules: torch, JAX and TensorFlow take means in float32, and
111+
pyclesperanto reduces only along the leading axis.

‎src/arraybridge/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
NumPy/numcodecs import cost.
1111
"""
1212

13-
__version__ = "0.3.8"
13+
__version__ = "0.4.0"
1414

1515
_LAZY_EXPORTS: dict[str, str] = {
1616
"MemoryType": ".types",

‎src/arraybridge/array_operations.py‎

Lines changed: 218 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,19 @@
1-
"""Native array operations carried by MemoryType declarations."""
1+
"""Native array operations, one family leaf per MemoryType declaration."""
22

3-
from abc import ABC, abstractmethod
4-
from collections.abc import Sequence
5-
from typing import Any
3+
from __future__ import annotations
4+
5+
from abc import abstractmethod
6+
from collections.abc import Mapping, Sequence
7+
from functools import cache, cached_property
8+
from typing import TYPE_CHECKING, Any, ClassVar
69

710
import numpy as np
11+
from metaclass_registry import AutoRegisterMeta
12+
13+
from arraybridge.array_payload import ArrayPayload
14+
15+
if TYPE_CHECKING:
16+
from arraybridge.types import MemoryType
817

918
_SCALING_RANGES: dict[str, float | tuple[float, float]] = {
1019
"uint8": 255.0,
@@ -68,8 +77,84 @@ def _mapped_dtype(target_dtype: Any, module: Any) -> Any:
6877
return mapped
6978

7079

71-
class ArrayOperations(ABC):
72-
"""Native array semantics selected by the existing MemoryType declaration."""
80+
@cache
81+
def _leaf_instance(leaf: type[ArrayOperations]) -> ArrayOperations:
82+
return leaf()
83+
84+
85+
class ArrayOperations(metaclass=AutoRegisterMeta):
86+
"""Native array semantics, one registered leaf per ``MemoryType`` value.
87+
88+
Static leaves take the framework module from their caller (``MemoryType``).
89+
Instance primitives are the namespace array-library-neutral code is written
90+
against: each leaf supplies only what its library genuinely does differently.
91+
"""
92+
93+
__registry_key__ = "memory_type"
94+
# Leaves are declared in this module, without lazy discovery.
95+
__registry__: ClassVar[Mapping[str, type[ArrayOperations]]] = {}
96+
memory_type: ClassVar[str | None] = None
97+
98+
@classmethod
99+
def for_memory(cls, memory_type: MemoryType) -> ArrayOperations:
100+
"""Return the operations leaf declared for ``memory_type``."""
101+
return _leaf_instance(cls.__registry__[memory_type.value])
102+
103+
@cached_property
104+
def module(self) -> Any:
105+
"""The framework module, imported on first use."""
106+
from arraybridge.types import MemoryType
107+
108+
return MemoryType(self.memory_type).import_module()
109+
110+
@property
111+
def array_module(self) -> Any:
112+
"""The module holding the framework's array functions."""
113+
return self.module
114+
115+
# ----- primitives for array-library-neutral operations -----
116+
117+
def accepts(self, value: Any) -> bool:
118+
"""Whether ``value`` is a native array of this framework."""
119+
return isinstance(value, self.module.ndarray)
120+
121+
def astype(self, data: Any, dtype: Any) -> Any:
122+
return self.cast(data, dtype, self.module)
123+
124+
def max(self, data: Any, axis: int | tuple[int, ...]) -> Any:
125+
return self.array_module.max(data, axis=axis)
126+
127+
def min(self, data: Any, axis: int | tuple[int, ...]) -> Any:
128+
return self.array_module.min(data, axis=axis)
129+
130+
def mean(self, data: Any, axis: int | tuple[int, ...]) -> Any:
131+
return self.array_module.mean(data, axis=axis)
132+
133+
def sum(self, data: Any, axis: int | tuple[int, ...]) -> Any:
134+
return self.array_module.sum(data, axis=axis)
135+
136+
def prepend_axis(self, data: Any) -> Any:
137+
"""Add a leading axis of length one."""
138+
return self.reshape(data, (1, *data.shape), self.module)
139+
140+
def linspace(self, start: float, stop: float, num: int, *, endpoint: bool) -> Any:
141+
return self.array_module.linspace(start, stop, num, endpoint=endpoint)
142+
143+
def ones(self, shape: int | tuple[int, ...], dtype: Any) -> Any:
144+
"""Allocate ones on the framework's default device."""
145+
return self.array_module.ones(shape, dtype=_mapped_dtype(dtype, self.array_module))
146+
147+
def assign(self, data: Any, index: slice, values: Any) -> Any:
148+
"""Return ``data`` with ``data[index]`` replaced by ``values``."""
149+
data[index] = values
150+
return data
151+
152+
def outer(self, left: Any, right: Any) -> Any:
153+
return self.array_module.outer(left, right)
154+
155+
def floor(self, value: float) -> Any:
156+
"""Floor a host scalar in the framework's default precision."""
157+
return self.array_module.floor(value)
73158

74159
@staticmethod
75160
@abstractmethod
@@ -160,6 +245,11 @@ def normalize_planes(
160245
class NumpyArrayOperations(MutableArrayOperations):
161246
"""Numpy native operation leaves."""
162247

248+
memory_type = "numpy"
249+
250+
def accepts(self, value: Any) -> bool:
251+
return isinstance(value, (np.ndarray, ArrayPayload))
252+
163253
@staticmethod
164254
def to_numpy(data: Any, module: Any) -> Any:
165255
del module
@@ -193,6 +283,8 @@ def scale_dtype(result: Any, target_dtype: Any, module: Any) -> Any:
193283
class CupyArrayOperations(MutableArrayOperations):
194284
"""Cupy native operation leaves."""
195285

286+
memory_type = "cupy"
287+
196288
@staticmethod
197289
def to_numpy(data: Any, module: Any) -> Any:
198290
del module
@@ -226,6 +318,35 @@ def scale_dtype(result: Any, target_dtype: Any, module: Any) -> Any:
226318
class TorchArrayOperations(ArrayOperations):
227319
"""Torch native operation leaves."""
228320

321+
memory_type = "torch"
322+
323+
def accepts(self, value: Any) -> bool:
324+
return isinstance(value, self.module.Tensor)
325+
326+
def max(self, data: Any, axis: int | tuple[int, ...]) -> Any:
327+
# CUDA has no uint16 reduction; float32 holds every uint16 exactly.
328+
values = data.float() if data.dtype == self.module.uint16 else data
329+
return self.module.amax(values, dim=axis).to(data.dtype)
330+
331+
def min(self, data: Any, axis: int | tuple[int, ...]) -> Any:
332+
values = data.float() if data.dtype == self.module.uint16 else data
333+
return self.module.amin(values, dim=axis).to(data.dtype)
334+
335+
def mean(self, data: Any, axis: int | tuple[int, ...]) -> Any:
336+
return self.module.mean(data.float(), dim=axis)
337+
338+
def sum(self, data: Any, axis: int | tuple[int, ...]) -> Any:
339+
return self.module.sum(data, dim=axis)
340+
341+
def linspace(self, start: float, stop: float, num: int, *, endpoint: bool) -> Any:
342+
float32 = self.module.float32
343+
if endpoint:
344+
return self.module.linspace(start, stop, num, dtype=float32)
345+
return self.module.linspace(start, stop, num + 1, dtype=float32)[:-1]
346+
347+
def floor(self, value: float) -> Any:
348+
return self.module.floor(self.module.tensor(value))
349+
229350
@staticmethod
230351
def to_numpy(data: Any, module: Any) -> Any:
231352
del module
@@ -264,11 +385,12 @@ def stack(values: Sequence[Any], module: Any) -> Any:
264385

265386
@staticmethod
266387
def cast(data: Any, dtype: Any, module: Any) -> Any:
267-
return data.to(dtype=_mapped_dtype(dtype, module))
388+
native = dtype if isinstance(dtype, module.dtype) else _mapped_dtype(dtype, module)
389+
return data.to(dtype=native)
268390

269391
@staticmethod
270392
def dtype_name(dtype: Any) -> str:
271-
return str(dtype).rsplit(".", maxsplit=1)[-1]
393+
return _torch_dtype_name(dtype)
272394

273395
@staticmethod
274396
def broadcast_to(data: Any, shape: tuple[int, ...], module: Any) -> Any:
@@ -282,6 +404,44 @@ def ones_like(reference: Any, shape: tuple[int, ...], dtype: Any, module: Any) -
282404
class TensorflowArrayOperations(ArrayOperations):
283405
"""Tensorflow native operation leaves."""
284406

407+
memory_type = "tensorflow"
408+
409+
def accepts(self, value: Any) -> bool:
410+
return isinstance(value, self.module.Tensor)
411+
412+
def max(self, data: Any, axis: int | tuple[int, ...]) -> Any:
413+
return self.module.reduce_max(data, axis=axis)
414+
415+
def min(self, data: Any, axis: int | tuple[int, ...]) -> Any:
416+
return self.module.reduce_min(data, axis=axis)
417+
418+
def mean(self, data: Any, axis: int | tuple[int, ...]) -> Any:
419+
return self.module.reduce_mean(self.module.cast(data, self.module.float32), axis=axis)
420+
421+
def sum(self, data: Any, axis: int | tuple[int, ...]) -> Any:
422+
return self.module.reduce_sum(data, axis=axis)
423+
424+
def linspace(self, start: float, stop: float, num: int, *, endpoint: bool) -> Any:
425+
if endpoint:
426+
return self.module.linspace(float(start), float(stop), num)
427+
return self.module.linspace(float(start), float(stop), num + 1)[:-1]
428+
429+
def assign(self, data: Any, index: slice, values: Any) -> Any:
430+
rows = self.module.range(*index.indices(int(data.shape[0])))
431+
return self.module.tensor_scatter_nd_update(
432+
data, self.module.reshape(rows, [-1, 1]), values
433+
)
434+
435+
def outer(self, left: Any, right: Any) -> Any:
436+
return self.module.tensordot(left, right, axes=0)
437+
438+
def floor(self, value: float) -> Any:
439+
return self.module.math.floor(value)
440+
441+
@staticmethod
442+
def dtype_name(dtype: Any) -> str:
443+
return _tensorflow_dtype_name(dtype)
444+
285445
@staticmethod
286446
def to_numpy(data: Any, module: Any) -> Any:
287447
del module
@@ -312,7 +472,8 @@ def scale_dtype(result: Any, target_dtype: Any, module: Any) -> Any:
312472

313473
@staticmethod
314474
def cast(data: Any, dtype: Any, module: Any) -> Any:
315-
return module.cast(data, _mapped_dtype(dtype, module))
475+
native = dtype if isinstance(dtype, module.dtypes.DType) else _mapped_dtype(dtype, module)
476+
return module.cast(data, native)
316477

317478
@staticmethod
318479
def reshape(data: Any, shape: tuple[int, ...], module: Any) -> Any:
@@ -327,6 +488,22 @@ def ones_like(reference: Any, shape: tuple[int, ...], dtype: Any, module: Any) -
327488
class JaxArrayOperations(ArrayOperations):
328489
"""Jax native operation leaves."""
329490

491+
memory_type = "jax"
492+
493+
@property
494+
def array_module(self) -> Any:
495+
return self.module.numpy
496+
497+
def accepts(self, value: Any) -> bool:
498+
return isinstance(value, self.module.numpy.ndarray)
499+
500+
def mean(self, data: Any, axis: int | tuple[int, ...]) -> Any:
501+
jnp = self.module.numpy
502+
return jnp.mean(data.astype(jnp.float32), axis=axis)
503+
504+
def assign(self, data: Any, index: slice, values: Any) -> Any:
505+
return data.at[index].set(values)
506+
330507
@staticmethod
331508
def to_numpy(data: Any, module: Any) -> Any:
332509
del module
@@ -388,6 +565,33 @@ def ones_like(reference: Any, shape: tuple[int, ...], dtype: Any, module: Any) -
388565
class PyclesperantoArrayOperations(ArrayOperations):
389566
"""Pyclesperanto native operation leaves."""
390567

568+
memory_type = "pyclesperanto"
569+
570+
def accepts(self, value: Any) -> bool:
571+
# pyclesperanto kernels push any host array they receive.
572+
return hasattr(value, "shape")
573+
574+
def max(self, data: Any, axis: int | tuple[int, ...]) -> Any:
575+
_require_z_axis(axis)
576+
return self.module.maximum_z_projection(data)
577+
578+
def min(self, data: Any, axis: int | tuple[int, ...]) -> Any:
579+
_require_z_axis(axis)
580+
return self.module.minimum_z_projection(data)
581+
582+
def mean(self, data: Any, axis: int | tuple[int, ...]) -> Any:
583+
_require_z_axis(axis)
584+
return self.module.mean_z_projection(data)
585+
586+
def sum(self, data: Any, axis: int | tuple[int, ...]) -> Any:
587+
_require_z_axis(axis)
588+
return self.module.sum_z_projection(data)
589+
590+
def prepend_axis(self, data: Any) -> Any:
591+
result = self.module.create((1, *data.shape), dtype=data.dtype)
592+
result[0] = data
593+
return result
594+
391595
@staticmethod
392596
def to_numpy(data: Any, module: Any) -> Any:
393597
return module.pull(data)
@@ -484,9 +688,8 @@ def ones_like(reference: Any, shape: tuple[int, ...], dtype: Any, module: Any) -
484688
return result
485689

486690

487-
NUMPY_OPERATIONS = NumpyArrayOperations()
488-
CUPY_OPERATIONS = CupyArrayOperations()
489-
TORCH_OPERATIONS = TorchArrayOperations()
490-
TENSORFLOW_OPERATIONS = TensorflowArrayOperations()
491-
JAX_OPERATIONS = JaxArrayOperations()
492-
PYCLESPERANTO_OPERATIONS = PyclesperantoArrayOperations()
691+
def _require_z_axis(axis: int | tuple[int, ...]) -> None:
692+
if axis != 0:
693+
raise NotImplementedError(
694+
f"pyclesperanto reduces only along the leading (z) axis, not axis {axis!r}"
695+
)

0 commit comments

Comments
 (0)