Skip to content

Commit 62bde8f

Browse files
trissimclaude
andcommitted
Tests and docs for the ArrayLibrary family; enum lookups by name see new libraries
Tests are regrouped by what they test (libraries, devices, conversion, memory type, toy library) with shared fake modules; tests of deleted modules are removed. Adds the toy-library test (one class gives lookup, MemoryType member, decorator and conversion), the light-import and plan-without-devices subprocess tests, and conversion record and counter tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 9906806 commit 62bde8f

50 files changed

Lines changed: 3132 additions & 3170 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/ci.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ jobs:
105105
# 1. Framework unavailable tests (always run)
106106
# 2. GPU unavailable fallback paths (will run in CI)
107107
# 3. Mocked GPU tests (test cleanup code with mocked GPU state)
108-
pytest -v tests/test_gpu_cleanup.py \
108+
pytest -v tests/test_libraries.py \
109109
--cov=arraybridge \
110110
--cov-report=term-missing \
111111
--cov-report=html \

‎.github/workflows/gpu-tests.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ jobs:
4646
run: |
4747
# Run all GPU cleanup tests
4848
# Tests will use frameworks if available, skip gracefully if not
49-
pytest -v tests/test_gpu_cleanup.py \
49+
pytest -v tests/test_libraries.py \
5050
--cov=arraybridge \
5151
--cov-report=term-missing \
5252
--cov-report=html \

‎ADDING_NEW_FRAMEWORKS.md‎

Lines changed: 168 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,180 @@
1-
# Adding a framework
1+
# Adding a library
22

3-
This is a maintainer how-to for extending ArrayBridge's closed framework
4-
taxonomy. Applications should consume `MemoryType`; they should not add their
5-
own framework registry.
3+
A library is one class: a subclass of `arraybridge.libraries.ArrayLibrary`
4+
that inherits the role parents it plays, states `name = "..."`, and defines
5+
the abstract methods those parents ask for. Nothing else is edited. The class
6+
can live in `src/arraybridge/libraries.py` or in any other module; it
7+
registers when its module is imported.
68

7-
## 1. Define typed leaves
9+
## What follows from the class
810

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:
11+
- Lookup: `ArrayLibrary.named(name)`, `ArrayLibrary.of(array)`,
12+
`ArrayLibrary.for_module_name(module_name)`, `ArrayLibrary.all()`.
13+
- A `MemoryType` member: `MemoryType.<NAME>` with value `name` and
14+
`.library` returning the library object.
15+
- The decorator `arraybridge.<name>`.
16+
- Conversion to and from every other library through `convert_memory`,
17+
`stack_slices` and `unstack_slices`. `ConversionRoute.planned` picks the
18+
route from the role parents: same library is a device move, a DLPack
19+
importer paired with a DLPack exporter is a DLPack exchange, anything else
20+
is a copy through NumPy.
21+
- Device answers (`host_devices`, `accelerator_devices`, `available_devices`,
22+
`require_device`) and the array operations (`max`, `reshape`,
23+
`stack_arrays`, ...) with NumPy-style defaults that call the library's
24+
module.
1225

13-
- project an array to NumPy;
14-
- create an array from NumPy on the requested framework-local device;
15-
- stack prepared 2D arrays into one 3D array;
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.
26+
## A host-only example
2027

21-
Define device, stream, DLPack, cleanup, and OOM leaves in
22-
`src/arraybridge/types.py`. Use the no-op defaults in `FrameworkRuntime` only
23-
when the framework genuinely lacks that capability. Do not encode behavior as
24-
strings or add a parallel `MemoryType`-keyed table.
28+
This file runs as it is with only NumPy installed.
2529

26-
## 2. Add the declaration
30+
```python
31+
import numpy as np
2732

28-
Add one `MemoryType` member carrying:
33+
from arraybridge import HOST, ConversionRoute, MemoryType
34+
from arraybridge import convert_memory, detect_memory_type, stack_slices
35+
from arraybridge.libraries import ArrayLibrary, HostDevices
2936

30-
1. its stable value and import name;
31-
2. its display name and module aliases;
32-
3. whether it is GPU-backed;
33-
4. any environment defaults that must be set before first import;
34-
5. its `FrameworkRuntime` leaves.
3537

36-
The converter classes, target conversion methods, compatibility operation view,
37-
dtype-scaling view, cleanup adapters, and framework decorator are generated
38-
from the enum. Do not wire them manually.
38+
class FrozenArray:
39+
"""Values in main memory that cannot be changed after creation."""
3940

40-
## 3. Prove the extension
41+
def __init__(self, values):
42+
self.values = np.array(values)
43+
self.values.flags.writeable = False
44+
self.shape = self.values.shape
45+
self.dtype = self.values.dtype
4146

42-
Add focused tests for:
47+
def __getitem__(self, index):
48+
return FrozenArray(self.values[index])
4349

44-
- module-name detection and optional-dependency failure;
45-
- NumPy round trips and every supported DLPack pair;
46-
- CPU-only installations of a nominally GPU framework;
47-
- invalid, negative, and multiple framework-local device IDs;
48-
- same-framework moves between two devices;
49-
- one-, two-, and multi-slice stack/unstack behavior;
50-
- immutable array types;
51-
- cleanup and OOM behavior without importing an absent framework;
52-
- generated registry and export completeness.
50+
51+
class FrozenLibrary(HostDevices[FrozenArray]):
52+
name = "frozen"
53+
# The module whose classes are this library's arrays. It defaults to
54+
# ``name``; here the array class lives in this file.
55+
import_name = __name__
56+
57+
# asked for by ArrayLibrary
58+
def device_of(self, data):
59+
return HOST
60+
61+
def _to_host(self, data):
62+
return np.array(data.values)
63+
64+
def _scale_dtype(self, result, target_dtype):
65+
return FrozenArray(result.values.astype(target_dtype))
66+
67+
# asked for by HostDevices
68+
def _wrap_host_array(self, data):
69+
return FrozenArray(data)
70+
71+
def _move_to_host(self, data):
72+
return data
73+
74+
# The inherited default calls ``self.module.stack``; this module has none.
75+
def _stack(self, values):
76+
return FrozenArray(np.stack([value.values for value in values]))
77+
78+
79+
# Lookup, by name and by array.
80+
library = ArrayLibrary.named("frozen")
81+
assert library in ArrayLibrary.all()
82+
assert ArrayLibrary.of(FrozenArray([1, 2])) is library
83+
84+
# The MemoryType member.
85+
assert MemoryType.FROZEN.value == "frozen"
86+
assert MemoryType.FROZEN.library is library
87+
88+
# Devices.
89+
assert library.available_devices() == (HOST,)
90+
91+
# Conversion in both directions, by host copy.
92+
numpy_library = ArrayLibrary.named("numpy")
93+
assert ConversionRoute.planned(numpy_library, HOST, library, HOST).mechanism == "host copy"
94+
frozen = convert_memory(np.arange(6).reshape(2, 3), "numpy", "frozen", HOST)
95+
assert detect_memory_type(frozen) == "frozen"
96+
assert convert_memory(frozen, "frozen", "numpy", HOST).tolist() == [[0, 1, 2], [3, 4, 5]]
97+
98+
# Stacking.
99+
stack = stack_slices([frozen, np.ones((2, 3))], "frozen", HOST)
100+
assert stack.shape == (2, 2, 3)
101+
102+
# The decorator named after the library.
103+
from arraybridge import frozen as frozen_function
104+
105+
106+
@frozen_function
107+
def first_row(image):
108+
return image[0]
109+
110+
111+
assert first_row.execution_memory_type == "frozen"
112+
assert first_row(frozen).shape == (3,)
113+
```
114+
115+
## What the class states
116+
117+
| Attribute | Meaning | Default |
118+
|---|---|---|
119+
| `name` | The registered name, the `MemoryType` value and the decorator name. | required |
120+
| `import_name` | Top-level module to import; objects from it belong to the library. | `name` |
121+
| `display_name` | Name used in messages. | `name` |
122+
| `module_aliases` | Other top-level module names whose objects belong to the library (JAX: `jaxlib`). | `()` |
123+
| `import_environment` | Environment variables set, if unset, before the first import and in child processes. | `()` |
124+
| `oom_messages` | Lower-case text that marks an out-of-memory error message. | `()` |
125+
| `oom_exception_paths` | Attribute paths from the module to its out-of-memory exception classes. | `()` |
126+
127+
Every library defines three methods asked for by `ArrayLibrary` itself:
128+
129+
- `device_of(data)`: the device holding the array. It never returns `None`.
130+
- `_to_host(data)`: the array as a NumPy array.
131+
- `_scale_dtype(result, target_dtype)`: convert the dtype, rescaling float
132+
intensities into the integer range where the library does that.
133+
134+
## Role parents
135+
136+
Inherit each role the library plays. The abstract methods are the ones the
137+
class must define.
138+
139+
| Parent | The library... | Abstract methods |
140+
|---|---|---|
141+
| `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()` |
144+
| `DLPackImport` | can wrap another library's buffer through DLPack. | `_import_dlpack(payload)` |
145+
| `DLPackProtocolExport` | has arrays with the standard DLPack export methods on every device. | none |
146+
| `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)` |
148+
149+
Methods with a default worth knowing:
150+
151+
- `HostDevices._host_scope()`: the block in which new arrays are created in
152+
main memory. The default does nothing; TensorFlow and JAX override it.
153+
- `AcceleratorDevices._activate_accelerator(device)`: select a device for the
154+
whole process. The default does nothing.
155+
- `cleanup_loaded(device=None)`: release cached device memory. `CudaLibrary`
156+
implements it; elsewhere the default does nothing.
157+
- `exports_dlpack_from`, `exports_dlpack_data`, `export_dlpack`: override
158+
these directly when export depends on the device or the array, as
159+
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.
165+
166+
The six built-in classes at the end of `src/arraybridge/libraries.py` are the
167+
reference for each combination of roles.
168+
169+
## Tests to add
170+
171+
- detection by array and by module name, and behaviour when the package is
172+
not installed;
173+
- NumPy round trips, and the planned route against every other library;
174+
- each device the library accepts, and `ValueError` for one it does not have;
175+
- moves between two devices of the library;
176+
- stacking and unstacking one, two and several planes;
177+
- cleanup and out-of-memory recognition without importing an absent library.
53178

54179
Run:
55180

@@ -61,6 +186,6 @@ pytest
61186
python -m sphinx -E -W --keep-going -b html docs/source /tmp/arraybridge-docs
62187
```
63188

64-
When GPU hardware is available, also exercise every installed framework pair in
65-
one process. This catches import-order, allocator-coexistence, DLPack, and real
66-
API-shape defects that isolated mocks cannot prove.
189+
When accelerator hardware is available, also convert between every installed
190+
pair of libraries in one process. Import order, allocators sharing a device
191+
and DLPack differences only show there.

‎CHANGELOG.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ GPU", which is false for torch, JAX and TensorFlow. Ask instead:
5252
| Where is this array? | `library.device_of(array)` (never `None`) |
5353

5454
Every `gpu_id` / `device_id` integer parameter is now a `Device`. A device the
55-
library does not have raises `ValueError`; in particular a NumPy target with an
55+
library does not have raises `ValueError` (`convert_memory` wraps it in
56+
`MemoryConversionError`, as it wraps every failure); in particular a NumPy target with an
5657
accelerator device raises (0.4.1 ignored the number), and torch, JAX and
5758
TensorFlow accept `HOST` (0.4.1 always moved torch data to CUDA).
5859
`process_slices` keeps a torch CPU tensor on the host (0.4.1 sent it to GPU 0).

‎CONTRIBUTING.md‎

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -117,29 +117,34 @@ git checkout -b fix/issue-description
117117
Use Google-style docstrings:
118118

119119
```python
120-
def convert_memory(data: Any, source_type: str, target_type: str, gpu_id: int) -> Any:
120+
def convert_memory(
121+
data: Array,
122+
source_type: str | MemoryType,
123+
target_type: str | MemoryType,
124+
device: Device,
125+
) -> Array:
121126
"""
122-
Convert data between memory types.
127+
Convert data from the source library to the target library on a device.
123128
124129
Args:
125-
data: The data to convert
130+
data: The array to convert
126131
source_type: The source memory type (e.g., "numpy", "torch")
127132
target_type: The target memory type (e.g., "cupy", "jax")
128-
gpu_id: The target GPU device ID
133+
device: The device of the target library to put the result on
129134
130135
Returns:
131-
The converted data in the target memory type
136+
The converted array in the target memory type
132137
133138
Raises:
134-
ValueError: If source_type or target_type is invalid
139+
ValueError: If source_type or target_type is not a registered library
135140
MemoryConversionError: If conversion fails
136141
137142
Example:
138143
import numpy as np
139-
from arraybridge import convert_memory
144+
from arraybridge import HOST, convert_memory
140145
141146
data = np.array([1, 2, 3])
142-
result = convert_memory(data, "numpy", "torch", gpu_id=0)
147+
result = convert_memory(data, "numpy", "torch", HOST)
143148
"""
144149
```
145150

@@ -159,22 +164,22 @@ def convert_memory(data: Any, source_type: str, target_type: str, gpu_id: int) -
159164
```python
160165
import pytest
161166
import numpy as np
162-
from arraybridge import convert_memory
167+
from arraybridge import HOST, convert_memory
163168

164169
class TestConvertMemory:
165170
"""Tests for convert_memory function."""
166171

167172
def test_convert_numpy_to_numpy(self):
168-
"""Test converting NumPy to NumPy (no-op)."""
173+
"""Converting NumPy to NumPy on the host returns the same array."""
169174
arr = np.array([1, 2, 3])
170-
result = convert_memory(arr, "numpy", "numpy", gpu_id=0)
171-
np.testing.assert_array_equal(result, arr)
175+
result = convert_memory(arr, "numpy", "numpy", HOST)
176+
assert result is arr
172177

173178
def test_invalid_source_type_raises_error(self):
174179
"""Test that invalid source type raises ValueError."""
175180
arr = np.array([1, 2, 3])
176181
with pytest.raises(ValueError):
177-
convert_memory(arr, "invalid", "numpy", gpu_id=0)
182+
convert_memory(arr, "invalid", "numpy", HOST)
178183
```
179184

180185
### Running Tests
@@ -400,18 +405,13 @@ GitHub Actions will automatically:
400405
4. **Test thoroughly**: Include unit, integration, and edge case tests
401406
5. **Maintain compatibility**: Avoid breaking changes when possible
402407

403-
### Adding Framework Support
408+
### Adding Library Support
404409

405-
To add support for a new framework:
406-
407-
1. Add one `ArrayOperations` leaf in `array_operations.py` declaring its `memory_type`.
408-
2. Add one `MemoryType` declaration carrying its runtime leaves.
409-
3. Add detection, conversion-pair, stack, cross-device, and optional-dependency tests.
410-
4. Update the extension and reference documentation.
411-
412-
Do not add framework behavior to `_FRAMEWORK_CONFIG`, a consumer registry, or
413-
generated decorator exports. See `ADDING_NEW_FRAMEWORKS.md` for the complete
414-
declaration-owned extension procedure.
410+
A new library is one class: a subclass of `ArrayLibrary` with the role parents
411+
it plays, `name = "..."`, and the abstract methods of those parents. Lookup,
412+
the `MemoryType` member, the decorator and the conversion routes follow from
413+
the class. See `ADDING_NEW_FRAMEWORKS.md` for a runnable example, the methods
414+
each role parent asks for, and the tests to add.
415415

416416
## Getting Help
417417

@@ -427,4 +427,4 @@ Contributors will be recognized in:
427427
- Release notes (for significant contributions)
428428
- Project README (for major features)
429429

430-
Thank you for contributing to arraybridge! 🎉
430+
Thank you for contributing to arraybridge!

0 commit comments

Comments
 (0)