Skip to content

Commit 9906806

Browse files
trissimclaude
andcommitted
DLPack planning knows which buffers a library can wrap; changelog for 0.5.0
A library without main-memory arrays (CuPy) cannot wrap a host buffer, so that pair is planned and run as a host copy instead of a DLPack attempt that fails. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 0f52089 commit 9906806

3 files changed

Lines changed: 134 additions & 1 deletion

File tree

‎CHANGELOG.md‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
# Changelog
2+
3+
## 0.5.0
4+
5+
Each supported array library is now one class of one family,
6+
`arraybridge.libraries.ArrayLibrary`. The class states the library's identity
7+
and owns everything that library does its own way: devices, moving data,
8+
streams, DLPack, out-of-memory recognition, child-process environment and
9+
native array operations. Adding a library is writing one class; lookup,
10+
conversion, the `MemoryType` member and the decorator follow from it.
11+
12+
This release removes names without aliases. The table says what to call
13+
instead.
14+
15+
### The family
16+
17+
| Class | Parents (roles) |
18+
|---|---|
19+
| `NumpyLibrary` | `HostDevices`, `MutableArrays` |
20+
| `CupyLibrary` | `CudaLibrary`, `DLPackImport`, `DLPackProtocolExport`, `NvidiaWheelLibraries`, `MutableArrays` |
21+
| `TorchLibrary` | `HostDevices`, `CudaLibrary`, `DLPackImport`, `DLPackProtocolExport` |
22+
| `TensorflowLibrary` | `HostDevices`, `AcceleratorDevices`, `DLPackImport` |
23+
| `JaxLibrary` | `HostDevices`, `AcceleratorDevices`, `DLPackImport`, `DLPackProtocolExport` |
24+
| `PyclesperantoLibrary` | `AcceleratorDevices` |
25+
26+
Lookup: `ArrayLibrary.named("torch")`, `ArrayLibrary.of(array)` (which library
27+
made this), `ArrayLibrary.for_module_name("jaxlib")`, `ArrayLibrary.all()`.
28+
29+
### `MemoryType`
30+
31+
`MemoryType` is kept as a view: an `Enum` whose members are generated from the
32+
registered library classes (`MemoryType.TORCH.value == "torch"`). It carries no
33+
behaviour. `MemoryType.X.library` is the library object. A library class
34+
defined later appears as a member.
35+
36+
### Devices
37+
38+
`arraybridge.devices`: `Device` with leaves `HostDevice()` (the value `HOST`),
39+
`AcceleratorDevice(index)` and `NamedDevice(name)` (a device the library
40+
reports that is not one of its numbered accelerators, such as pyclesperanto on
41+
a CPU OpenCL device). Each has a `label`.
42+
43+
`is_gpu` is removed. It answered "is this NumPy" and was read as "this needs a
44+
GPU", which is false for torch, JAX and TensorFlow. Ask instead:
45+
46+
| Question | Call |
47+
|---|---|
48+
| Does the library keep arrays in main memory? | `isinstance(library, HostDevices)`; `library.host_devices()` |
49+
| Can the library use accelerators at all? | `isinstance(library, AcceleratorDevices)` |
50+
| Which accelerators exist on this machine now? | `library.accelerator_devices()` |
51+
| Every device it can use now | `library.available_devices()` |
52+
| Where is this array? | `library.device_of(array)` (never `None`) |
53+
54+
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
56+
accelerator device raises (0.4.1 ignored the number), and torch, JAX and
57+
TensorFlow accept `HOST` (0.4.1 always moved torch data to CUDA).
58+
`process_slices` keeps a torch CPU tensor on the host (0.4.1 sent it to GPU 0).
59+
60+
### Conversion
61+
62+
`arraybridge.conversion`:
63+
64+
- `ConversionRoute`: the mechanisms, tried in declaration order: `DeviceMove`
65+
(`"device move"`), `DLPackExchange` (`"dlpack"`), `HostCopy` (`"host copy"`).
66+
`ConversionRoute.planned(source_library, source_device, target_library,
67+
target_device)` returns the route that will be tried first. It reads only
68+
the library declarations and the device values: no device, no import. The
69+
conversion itself selects its route with the same test.
70+
- `ConversionRecord`: source and target library and device label, mechanism,
71+
`nbytes`, `seconds`, and `declined_mechanisms` (routes that applied by
72+
declaration but could not carry that array). Plain fields; `to_json()`,
73+
`from_json()`.
74+
- `ConversionObserver`: one hook, `ConversionObserver.current`. The default
75+
ignores conversions and nothing is timed. `observer.install()` or
76+
`with observer.installed():`. `convert_to`, `to_numpy` and `from_numpy`
77+
report; a call that returns its input unchanged does not.
78+
- `ConversionCounters`: an observer keeping totals per (source, target,
79+
mechanism); `merge`, `rows`, `to_json`, `from_json`, `format_table`.
80+
81+
DLPack is no longer attempted from a main-memory buffer into CuPy, which
82+
cannot wrap one; the result (a host copy) is unchanged and the warning is gone.
83+
84+
### Removed, and what to call instead
85+
86+
| Removed | Use |
87+
|---|---|
88+
| `MemoryType.X.<method>(...)` (any method) | `MemoryType.X.library.<method>(...)` |
89+
| the `module=` argument of those methods | gone; the library uses its imported module |
90+
| `MemoryType.is_gpu` | see Devices |
91+
| `CPU_MEMORY_TYPES`, `GPU_MEMORY_TYPES` | filter `MemoryType` by `isinstance(m.library, HostDevices / AcceleratorDevices)` |
92+
| `SUPPORTED_MEMORY_TYPES`, `VALID_MEMORY_TYPES`, `VALID_GPU_MEMORY_TYPES`, `MEMORY_TYPE_*` | `MemoryType` itself; `m.value` |
93+
| `device_id_of(data)` | `library.device_of(data)` |
94+
| `available_device_ids()` | `library.accelerator_devices()` |
95+
| `require_device(id)` returning the module | `library.require_device(device)` returns `None`; `library.module` |
96+
| `canonical_dtype_name(dtype)` | `library.dtype_name(dtype)` |
97+
| `supports_dlpack` | `library.imports_dlpack`, `library.imports_dlpack_from(device)` |
98+
| `supports_dlpack_data(data)` | `library.exports_dlpack_data(data)` |
99+
| `current_device_id()`, `create_stream()` | on `CudaLibrary` only: `current_device()`, `create_stream()`, `thread_stream(device)` |
100+
| `MemoryType.subprocess_environment(env)` | `ArrayLibrary.child_environment(env)` |
101+
| `arraybridge.types.FrameworkRuntime` and the `_<library>_<capability>` functions | methods of the library classes |
102+
| `arraybridge.types.DLPackPayload` | `arraybridge.libraries.DLPackPayload` |
103+
| `arraybridge.array_operations.ArrayOperations`, `ArrayOperations.for_memory(m)` | `ArrayLibrary`, `m.library` (same primitive names) |
104+
| `ArrayOperations.to_numpy(data, module)` and the other `module`-taking leaves | the library method without `module`: `to_numpy(data)`, `from_numpy(data, device)`, `scale_dtype`, `stack_arrays(values, device)`, `astype`, `logical_and`, `reshape`, `broadcast_to`, `ones_like`, `normalize_planes` |
105+
| `arraybridge.framework_config`, `framework_ops`, `_FRAMEWORK_CONFIG`, `_FRAMEWORK_OPS` | nothing used them |
106+
| `arraybridge.converters_registry` (`ConverterBase`, `get_converter`) | `library.convert_to(data, target_library, device)` |
107+
| `arraybridge.dtype_scaling.SCALING_FUNCTIONS` | `library.scale_dtype(data, dtype)` |
108+
| `arraybridge.gpu_cleanup.cleanup_all_gpu_frameworks(device_id)` | `ArrayLibrary.cleanup_all_loaded(device)` |
109+
| `cleanup_<library>_gpu`, `MEMORY_TYPE_CLEANUP_REGISTRY` | `library.cleanup_loaded(device)` |
110+
| `arraybridge.oom_recovery._execute_with_oom_recovery(f, name, retries, device_id)` | `library.run_with_oom_recovery(f, retries, device)` |
111+
| `_is_oom_error(e, name)` | `library.is_oom_error(e)` |
112+
| `arraybridge.utils._get_device_id`, `_set_device`, `_move_to_device` | `library.device_of`, `activate_device`, `move_to_device` |
113+
| `arraybridge.decorators.ThreadGPUContext` | `CudaLibrary.thread_stream(device)`; per-call wrapping is `library.execution_wrapper(func, oom_recovery)` |
114+
| `convert_memory(..., gpu_id=)`, `stack_slices(..., gpu_id=)`, `unstack_slices(..., gpu_id=)`, `process_slices(..., gpu_id=)` | the same functions with `device` |
115+
116+
### Typing
117+
118+
`typing.Any` is not used in the package. `arraybridge.arrays.Array` is the
119+
nominal type of an array of any supported library; `library.array_class` is an
120+
array of that library. Native array classes are registered with them when a
121+
library first meets one.

‎src/arraybridge/conversion.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,9 @@ class DLPackExchange(ConversionRoute):
149149

150150
@classmethod
151151
def applies(cls, source, source_device, target, target_device) -> bool:
152-
return target.imports_dlpack and source.exports_dlpack_from(source_device)
152+
return target.imports_dlpack_from(source_device) and source.exports_dlpack_from(
153+
source_device
154+
)
153155

154156
@classmethod
155157
def convert(cls, data, source, target, target_device):

‎src/arraybridge/libraries.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -460,6 +460,12 @@ def imports_dlpack(self) -> bool:
460460

461461
return isinstance(self, DLPackImport)
462462

463+
def imports_dlpack_from(self, device: Device) -> bool:
464+
"""Whether this library can wrap a buffer that lives on ``device``."""
465+
466+
del device
467+
return False
468+
463469
def exports_dlpack_from(self, device: Device) -> bool:
464470
"""Whether arrays of this library on ``device`` are offered through DLPack."""
465471

@@ -886,6 +892,10 @@ def cleanup_loaded(self, device: AcceleratorDevice | None = None) -> None:
886892
class DLPackImport(ArrayLibrary[NativeT]):
887893
"""Libraries that can wrap another library's buffer handed over through DLPack."""
888894

895+
def imports_dlpack_from(self, device: Device) -> bool:
896+
# A library without main-memory arrays cannot wrap a main-memory buffer.
897+
return isinstance(self, HostDevices) or not isinstance(device, HostDevice)
898+
889899
def from_dlpack(self, data: DLPackPayload | object) -> NativeT:
890900
"""Wrap an exported buffer; ``NotImplemented`` when this capsule cannot be read."""
891901

0 commit comments

Comments
 (0)