Skip to content

Commit ae0da21

Browse files
authored
Merge pull request #13 from OpenHCSDev/refactor/sound-array-defaults
0.5.1: no inherited operation a library cannot perform; host calls leave the accelerator alone; warn_return_any on
2 parents 0aecbe4 + 60b9662 commit ae0da21

38 files changed

Lines changed: 1812 additions & 326 deletions

‎.github/workflows/ci.yml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,8 @@ jobs:
152152
run: |
153153
black --check src/
154154
155+
# stubs/ declares what arraybridge calls of each library it imports, so
156+
# nothing but mypy needs installing; naming it checks the declarations too.
155157
- name: Run mypy (type checking)
156158
run: |
157-
mypy src/
159+
mypy src/ stubs/

‎ADDING_NEW_FRAMEWORKS.md‎

Lines changed: 92 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,45 @@ class FrozenLibrary(HostDevices[FrozenArray]):
7171
def _move_to_host(self, data):
7272
return data
7373

74-
# The inherited default calls ``self.module.stack``; this module has none.
74+
# Array operations: nothing is inherited for them, because the
75+
# base class assumes no array API. This array wraps NumPy values.
76+
def accepts(self, value):
77+
return isinstance(value, FrozenArray)
78+
79+
def max(self, data, axis):
80+
return FrozenArray(data.values.max(axis=axis))
81+
82+
def min(self, data, axis):
83+
return FrozenArray(data.values.min(axis=axis))
84+
85+
def mean(self, data, axis):
86+
return FrozenArray(data.values.mean(axis=axis))
87+
88+
def sum(self, data, axis):
89+
return FrozenArray(data.values.sum(axis=axis))
90+
91+
def assign(self, data, index, values):
92+
updated = data.values.copy()
93+
updated[index] = values.values
94+
return FrozenArray(updated)
95+
7596
def _stack(self, values):
7697
return FrozenArray(np.stack([value.values for value in values]))
98+
99+
def _cast(self, data, dtype):
100+
return FrozenArray(data.values.astype(dtype))
101+
102+
def _logical_and(self, left, right):
103+
return FrozenArray(np.logical_and(left.values, right.values))
104+
105+
def _reshape(self, data, shape):
106+
return FrozenArray(data.values.reshape(shape))
107+
108+
def _broadcast_to(self, data, shape):
109+
return FrozenArray(np.broadcast_to(data.values, shape))
110+
111+
def _ones_like(self, reference, shape, dtype):
112+
return FrozenArray(np.ones(shape, dtype=dtype))
77113

78114

79115
# Lookup, by name and by array.
@@ -124,7 +160,8 @@ assert first_row(frozen).shape == (3,)
124160
| `oom_messages` | Lower-case text that marks an out-of-memory error message. | `()` |
125161
| `oom_exception_paths` | Attribute paths from the module to its out-of-memory exception classes. | `()` |
126162

127-
Every library defines three methods asked for by `ArrayLibrary` itself:
163+
Every library defines three methods asked for by `ArrayLibrary` itself, and
164+
the array operations listed under "Array operations" below:
128165

129166
- `device_of(data)`: the device holding the array. It never returns `None`.
130167
- `_to_host(data)`: the array as a NumPy array.
@@ -139,12 +176,11 @@ class must define.
139176
| Parent | The library... | Abstract methods |
140177
|---|---|---|
141178
| `HostDevices` | keeps arrays in main memory. | `_wrap_host_array(data)`, `_move_to_host(data)` |
142-
| `AcceleratorDevices` | can keep arrays on numbered accelerators. | `_accelerator_count()`, `_accelerator_scope(device)`, `_move_to_accelerator(data, device)`, `_upload(data, device)` |
143-
| `CudaLibrary` | is an `AcceleratorDevices` library with its own CUDA streams and a memory cache to release. | those of `AcceleratorDevices`, plus `stream_scope(stream)`, `current_device()`, `_free_cached_memory()` |
179+
| `AcceleratorDevices` | can keep arrays on numbered accelerators. | `_accelerator_count()`, `_accelerator_scope(device)`, `_move_to_accelerator(data, device)`, `_upload(data, device)`, `_device_if_accepted(value)` |
180+
| `CudaLibrary` | is an `AcceleratorDevices` library with its own CUDA streams and a memory cache to release. | those of `AcceleratorDevices`, plus `create_stream()`, `stream_scope(stream)`, `current_device()`, `_free_cached_memory()` |
144181
| `DLPackImport` | can wrap another library's buffer through DLPack. | `_import_dlpack(payload)` |
145182
| `DLPackProtocolExport` | has arrays with the standard DLPack export methods on every device. | none |
146183
| `NvidiaWheelLibraries` | loads CUDA from the `nvidia-*` wheels; child processes get their library directories on the search path. | none |
147-
| `MutableArrays` | has the NumPy array API and arrays that can be changed in place; supplies `_scale_dtype` and in-place plane normalisation. | `_rescales_into(target_dtype)` |
148184

149185
Methods with a default worth knowing:
150186

@@ -154,18 +190,63 @@ Methods with a default worth knowing:
154190
whole process. The default does nothing.
155191
- `cleanup_loaded(device=None)`: release cached device memory. `CudaLibrary`
156192
implements it; elsewhere the default does nothing.
193+
- `DLPackImport._reads_dlpack(payload)`: whether the importer can read this
194+
payload. The default says yes; where it says no, `from_dlpack` returns
195+
`NotImplemented` and `_import_dlpack` is not called.
157196
- `exports_dlpack_from`, `exports_dlpack_data`, `export_dlpack`: override
158197
these directly when export depends on the device or the array, as
159198
TensorFlow does.
160-
- `_stack`, `_cast`, `_reshape`, `_broadcast_to`, `_ones_like`,
161-
`_logical_and`, `max`, `min`, `mean`, `sum`, `linspace`, `ones`, `assign`,
162-
`outer`, `floor`, `accepts`, `nbytes_of`, `dtype_name`: the defaults call
163-
NumPy-named functions on the library's module or methods on the array.
164-
Override each one whose call or numeric rule differs.
199+
- `nbytes_of`, `dtype_name`: the defaults read `shape` and `dtype` from the
200+
array and name the dtype as NumPy does. Override where the library differs.
201+
202+
## Array operations
203+
204+
`ArrayLibrary` asks every library for `accepts`, `max`, `min`, `mean`, `sum`,
205+
`assign`, `_stack`, `_cast`, `_reshape`, `_broadcast_to`, `_ones_like` and
206+
`_logical_and`, and gives no default for any of them: the base class assumes
207+
no array API. A library defines them or inherits them from a parent it
208+
declares.
209+
210+
| Parent | The library... | Supplies | Abstract methods |
211+
|---|---|---|---|
212+
| `InPlaceAssignment` | has arrays that take `array[index] = values`. | `assign` | none |
213+
| `ArrayMath` | can make arrays without a reference array, on its default device. A library that cannot (pyclesperanto) does not inherit it and has none of these four methods. | nothing | `linspace`, `ones`, `outer`, `floor` |
214+
| `NumpyArrayApi` | has an array module and arrays that follow the NumPy API (`array_module.max(data, axis=...)`, `data.astype(...)`, ...). It is an `ArrayMath` library. | every operation above except `assign`, and the four of `ArrayMath` | `array_module` |
215+
| `MutableArrays` | is a `NumpyArrayApi` and `InPlaceAssignment` library; supplies `_scale_dtype` and in-place plane normalisation. | all of the above | `array_module`, `_rescales_into(target_dtype)` |
216+
217+
Override an inherited operation only where the library's numeric rule
218+
differs (JAX's `mean` casts to float32 first).
165219

166220
The six built-in classes at the end of `src/arraybridge/libraries.py` are the
167221
reference for each combination of roles.
168222

223+
## Typing
224+
225+
The checker reads a library from `stubs/<library>/`, never from an installed
226+
copy, so `mypy` gives the same result on every machine. For a new library:
227+
228+
- declare in `stubs/<library>/` exactly the functions, classes and attributes
229+
the class calls, with the library's own names and types;
230+
- state the module in the class, so its calls are checked against that
231+
declaration:
232+
233+
```python
234+
if TYPE_CHECKING:
235+
import mylib
236+
237+
class MylibLibrary(HostDevices["mylib.Array"]):
238+
name = "mylib"
239+
240+
if TYPE_CHECKING:
241+
module = mylib
242+
```
243+
244+
- call `self.module.<function>(...)` directly: a local `module = self.module`
245+
is a plain `ModuleType` to the checker and loses the declaration;
246+
- a `NumpyArrayApi` library returns its module of NumPy-named functions from
247+
`array_module`; the checker compares that module with the `NumpyFunctions`
248+
Protocol (`MutableNumpyFunctions` for `MutableArrays`).
249+
169250
## Tests to add
170251

171252
- detection by array and by module name, and behaviour when the package is
@@ -181,7 +262,7 @@ Run:
181262
```bash
182263
ruff check src tests
183264
black --check src tests
184-
mypy src --ignore-missing-imports
265+
mypy src stubs
185266
pytest
186267
python -m sphinx -E -W --keep-going -b html docs/source /tmp/arraybridge-docs
187268
```

‎CHANGELOG.md‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,89 @@
11
# Changelog
22

3+
## 0.5.1
4+
5+
### No library inherits an operation it cannot perform
6+
7+
`ArrayLibrary` no longer supplies NumPy-style implementations. In 0.5.0 every
8+
library inherited `self.array_module.linspace(...)`, `.ones`, `.outer`,
9+
`.floor`, `.max(axis=...)`, `data.astype(...)` and so on, whether or not its
10+
module had those functions. They now live in parents a library declares:
11+
12+
| Parent | Supplies | Inherited by |
13+
|---|---|---|
14+
| `NumpyArrayApi` | every array operation, by NumPy's names on `array_module` | NumPy, CuPy, JAX |
15+
| `ArrayMath` | declares `linspace`, `ones`, `outer`, `floor` (abstract) | `NumpyArrayApi`, torch, TensorFlow |
16+
| `InPlaceAssignment` | `assign` by `array[index] = values` | `MutableArrays` (NumPy, CuPy), torch, pyclesperanto |
17+
18+
`MutableArrays` is now a `NumpyArrayApi` and `InPlaceAssignment` library.
19+
`accepts`, `max`, `min`, `mean`, `sum`, `assign`, `_stack`, `_cast`,
20+
`_reshape`, `_broadcast_to`, `_ones_like` and `_logical_and` are abstract in
21+
`ArrayLibrary`. Torch and TensorFlow state the few they used to inherit; JAX
22+
drops four overrides that only repeated the NumPy spelling.
23+
24+
What changes for callers: `PyclesperantoLibrary` has no `linspace`, `ones`,
25+
`outer` or `floor`. In 0.5.0 `ArrayLibrary.named("pyclesperanto").linspace(...)`
26+
existed and failed inside the call; it is now an `AttributeError` at the
27+
attribute. Ask `isinstance(library, ArrayMath)`. Nothing else is renamed or
28+
removed, and every other built-in library answers every operation as before.
29+
30+
What changes for a library class written outside the package: it defines the
31+
operations above or inherits `NumpyArrayApi` (`ADDING_NEW_FRAMEWORKS.md` shows
32+
both).
33+
34+
### A decorated call in main memory does not touch the accelerator
35+
36+
The wrapper a library decorator puts around a function (`execution_wrapper`)
37+
reads the device from the call's arguments. In 0.5.0 it asked the library for
38+
its selected device whenever the machine had an accelerator, which for torch
39+
calls `torch.cuda.current_device()`: CUDA was initialised and a stream opened
40+
for a function working on host tensors.
41+
42+
- Arguments held on accelerator N: the call runs on this thread's stream for
43+
device N, with out-of-memory recovery for that device. (0.5.0 used the
44+
stream of the selected device even when the data was on another one.)
45+
- Arguments in main memory, or no array of a library that has main memory
46+
(torch, TensorFlow, JAX): the function is called as written. Nothing of the
47+
accelerator is asked, and there is no out-of-memory retry.
48+
- A library without main memory (CuPy, pyclesperanto) called without one of
49+
its arrays runs on its selected device, as before.
50+
51+
### Typing
52+
53+
`mypy` runs with `warn_return_any` and without `ignore_missing_imports`. Every
54+
library the package imports is declared in the repository's `stubs/`
55+
directory, which lists what arraybridge calls and comes before any installed
56+
copy, so the result is the same on every machine. A library class states that
57+
its `module` is that library; `NumpyArrayApi` names its module by the
58+
`NumpyFunctions` Protocol. For a class written outside the package this means:
59+
`NumpyArrayApi` and `MutableArrays` leave `array_module` abstract,
60+
`AcceleratorDevices` asks for `_device_if_accepted(value)`, `CudaLibrary` for
61+
`create_stream()`, and a `DLPackImport` library that cannot read a payload says
62+
so in `_reads_dlpack(payload)` instead of returning `NotImplemented` from
63+
`_import_dlpack`.
64+
65+
Annotations that now say what was already returned: a device or stream scope
66+
is an `AbstractContextManager[object]` (CuPy's device and stream are their own
67+
context managers), `from_dlpack` returns the array or `NotImplementedType`,
68+
and `ArrayLibrary.array_module` is an `object` in the base class.
69+
70+
A value of the wrong kind is now refused with `TypeError` in four places:
71+
`MemoryContractAttribute.read` when the stored value is neither a string nor
72+
`None`, `TorchLibrary.stream_scope` for an object that is neither a
73+
`torch.cuda.Stream` nor `None`, a dtype lookup in torch or TensorFlow whose
74+
attribute is not a dtype of that library, and `DeviceMove.convert` called with
75+
two different libraries.
76+
77+
`MemoryType`'s metaclass overrides are annotated with `EnumMeta`'s signatures;
78+
its `__call__` override is gone (`Enum` already asks `_missing_`).
79+
80+
### Not verified on a GPU
81+
82+
0.5.1 was tested with NumPy on Python 3.10, 3.12 and 3.13 and with the torch
83+
CPU wheel on 3.12. CuPy, TensorFlow, JAX and pyclesperanto, and torch on CUDA,
84+
were exercised only through the fakes in `tests/fakes.py`. `TESTING.md` has
85+
the commands for a GPU machine.
86+
387
## 0.5.0
488

589
Each supported array library is now one class of one family,
@@ -120,3 +204,4 @@ cannot wrap one; the result (a host copy) is unchanged and the warning is gone.
120204
nominal type of an array of any supported library; `library.array_class` is an
121205
array of that library. Native array classes are registered with them when a
122206
library first meets one.
207+

‎CONTRIBUTING.md‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ ruff check src/ tests/ --fix
250250

251251
```bash
252252
# Run type checker
253-
mypy src/ --ignore-missing-imports
253+
mypy src stubs
254254

255255
# Check specific file
256256
mypy src/arraybridge/converters.py
@@ -274,7 +274,7 @@ pytest
274274
pytest --cov=arraybridge --cov-report=term
275275

276276
# 5. Type check (optional but recommended)
277-
mypy src/ --ignore-missing-imports
277+
mypy src stubs
278278
```
279279

280280
## Submitting Changes
@@ -355,7 +355,7 @@ Add release notes to `CHANGELOG.md` (if exists) or create GitHub release notes.
355355
```bash
356356
ruff check src tests scripts
357357
black --check src scripts
358-
mypy src --ignore-missing-imports
358+
mypy src stubs
359359
pytest
360360
python -m sphinx -E -W --keep-going -b html docs/source /tmp/arraybridge-docs
361361
git commit
@@ -403,7 +403,6 @@ GitHub Actions will automatically:
403403
2. **Start small**: Begin with MVP, iterate based on feedback
404404
3. **Document**: Add docstrings, update README/docs
405405
4. **Test thoroughly**: Include unit, integration, and edge case tests
406-
5. **Maintain compatibility**: Avoid breaking changes when possible
407406

408407
### Adding Library Support
409408

‎README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,9 @@ that library, on the device of their input: `max`, `min`, `mean`, `sum`,
147147
`astype`, `reshape`, `broadcast_to`, `ones_like`, `ones`, `prepend_axis`,
148148
`linspace`, `assign`, `outer`, `floor`, `logical_and`, `stack_arrays`,
149149
`normalize_planes`, `scale_dtype`, `to_numpy`, `from_numpy`.
150+
`linspace`, `ones`, `outer` and `floor` exist only on libraries that can make
151+
an array without a reference array (`ArrayMath`: every built-in library but
152+
pyclesperanto).
150153

151154
```python
152155
import numpy as np

‎TESTING.md‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ are the authority for the current CI matrix.
99
python -m pip install -e ".[dev,docs]"
1010
ruff check src tests
1111
black --check src tests
12-
mypy src --ignore-missing-imports
12+
mypy src stubs
1313
pytest
1414
python -m sphinx -E -W --keep-going -b html docs/source /tmp/arraybridge-docs
1515
```
@@ -37,6 +37,41 @@ that declaration-owned import defaults work. Framework warnings about shared
3737
CUDA plugin registration should be recorded separately from value, device, or
3838
shape failures.
3939

40+
## Commands for a GPU machine
41+
42+
0.5.0's GPU run predates three later fixes, and 0.5.1 was not run on a GPU.
43+
On a machine with CUDA 12 and about 15 GB of free disk:
44+
45+
```bash
46+
git clone https://github.com/OpenHCSDev/ArrayBridge.git && cd ArrayBridge
47+
git checkout v0.5.1
48+
uv venv -p 3.12 .venv-gpu
49+
uv pip install -p .venv-gpu/bin/python -e ".[dev,gpu]"
50+
.venv-gpu/bin/python -m pytest -q --no-cov -ra
51+
.venv-gpu/bin/python -m pytest -q --no-cov -ra -m "gpu or cupy or torch or tensorflow or jax or pyclesperanto"
52+
.venv-gpu/bin/python -m pytest -q --no-cov -ra tests/test_operation_soundness.py
53+
.venv-gpu/bin/python host_call_check.py
54+
```
55+
56+
`tests/test_operation_soundness.py` calls every array operation of every
57+
installed library on its first device; no skip should name an installed
58+
library. `host_call_check.py` is:
59+
60+
```python
61+
import torch
62+
from arraybridge import torch as on_torch
63+
64+
@on_torch
65+
def add_one(image):
66+
return image + 1
67+
68+
add_one(torch.ones(2, 3, 3))
69+
assert not torch.cuda.is_initialized(), "a host call initialised CUDA"
70+
if torch.cuda.is_available():
71+
assert add_one(torch.ones(2, 3, 3, device="cuda:0")).is_cuda
72+
print("ok")
73+
```
74+
4075
## Interpreting CI
4176

4277
The main CI workflow runs the test suite across its declared Python and OS

‎docs/source/ci-cd.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ Before opening a change, run:
1212
python -m pytest
1313
ruff check src tests
1414
black --check src tests
15-
mypy src --ignore-missing-imports
15+
mypy src stubs
1616
1717
Documentation changes should also build with warnings as errors:
1818

‎docs/source/contributing.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ by the repository:
99
python -m pip install -e ".[dev,docs]"
1010
ruff check src tests
1111
black --check src tests
12-
mypy src --ignore-missing-imports
12+
mypy src stubs
1313
python -m pytest
1414
python -m sphinx -E -W --keep-going -b html docs/source docs/source/_build/html
1515

‎pyproject.toml‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -129,17 +129,18 @@ target-version = "py310"
129129
[tool.ruff.lint]
130130
select = ["E", "F", "I", "N", "W", "UP"]
131131

132+
[tool.ruff.lint.per-file-ignores]
133+
# The declarations in stubs/ carry the libraries' own names.
134+
"stubs/**" = ["N801", "N802"]
135+
132136
[tool.mypy]
133137
python_version = "3.10"
134138
follow_imports_for_stubs = true
135-
ignore_missing_imports = true
136-
# Optional array libraries are not importable by the checker, so what their
137-
# modules return is untyped; those values are admitted by Array registration
138-
# at runtime (see arraybridge.libraries).
139-
warn_return_any = false
139+
ignore_missing_imports = false
140+
# The optional array libraries are read from the declarations in stubs/, which
141+
# list what arraybridge calls and come before any installed copy, so the result
142+
# does not depend on what is installed where mypy runs.
143+
mypy_path = "$MYPY_CONFIG_FILE_DIR/stubs"
144+
warn_return_any = true
140145
warn_unused_configs = true
141146
disallow_untyped_defs = false # Too strict for scientific code
142-
143-
[[tool.mypy.overrides]]
144-
module = "numpy.*"
145-
follow_imports = "skip"

0 commit comments

Comments
 (0)