Skip to content

Commit 6f69ea4

Browse files
authored
Merge pull request #14 from OpenHCSDev/refactor/conversion-routes-say-what-happens
0.5.1: conversion routes say what happens; the observer belongs to its context
2 parents ae0da21 + ec0869e commit 6f69ea4

13 files changed

Lines changed: 716 additions & 107 deletions

File tree

‎ADDING_NEW_FRAMEWORKS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,7 @@ class must define.
176176
| Parent | The library... | Abstract methods |
177177
|---|---|---|
178178
| `HostDevices` | keeps arrays in main memory. | `_wrap_host_array(data)`, `_move_to_host(data)` |
179+
| `NumpyBufferSharing` | is a `HostDevices` library whose main-memory array and a NumPy array can be one buffer (measure it before declaring it). | those of `HostDevices`, plus `_first_element_address(data)` |
179180
| `AcceleratorDevices` | can keep arrays on numbered accelerators. | `_accelerator_count()`, `_accelerator_scope(device)`, `_move_to_accelerator(data, device)`, `_upload(data, device)`, `_device_if_accepted(value)` |
180181
| `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()` |
181182
| `DLPackImport` | can wrap another library's buffer through DLPack. | `_import_dlpack(payload)` |

‎CHANGELOG.md‎

Lines changed: 103 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,12 +77,112 @@ two different libraries.
7777
`MemoryType`'s metaclass overrides are annotated with `EnumMeta`'s signatures;
7878
its `__call__` override is gone (`Enum` already asks `_missing_`).
7979

80+
### Conversion
81+
82+
The mechanism names a consumer can now see, in the order the routes are tried:
83+
84+
| Mechanism | Route class | Meaning |
85+
|---|---|---|
86+
| `"stays in place"` | `StaysInPlace` (new) | Same library, same device. Nothing is converted; the input object is returned. No record. |
87+
| `"device move"` | `DeviceMove` | Same library, another device. |
88+
| `"dlpack"` | `DLPackExchange` | The target wraps the source's buffer through DLPack. |
89+
| `"shared host buffer"` | `SharedHostBuffer` (new) | Both arrays are in main memory and the result begins at the same address as the source: no bytes were copied. |
90+
| `"host copy"` | `HostCopy` | The values were copied through a NumPy array in main memory. |
91+
92+
**The plan and the run agree that nothing is converted.**
93+
`ConversionRoute.planned(library, device, library, device)` returns
94+
`StaysInPlace`. In 0.5.0 it returned `DeviceMove`, while running that
95+
conversion returned the input and recorded nothing, so a caller had to restate
96+
the rule. `DeviceMove` now applies only when the device differs. The rule is
97+
stated once, in `StaysInPlace.applies`; `convert_to`, `to_numpy`, `from_numpy`
98+
and `move_to_device` all ask it. Every route has `writes_a_record`; it is
99+
`False` for `StaysInPlace` only. A record means data was moved, copied or
100+
wrapped.
101+
102+
**A host exchange that shares the buffer is no longer called a copy.** On the
103+
host, torch and NumPy share one buffer in both directions, and JAX hands NumPy
104+
its own buffer; 0.5.0 recorded these as `"host copy"`. They are now recorded
105+
as `"shared host buffer"`. A library declares that it can share by inheriting
106+
`NumpyBufferSharing` (NumPy, torch and JAX do; TensorFlow copies in both
107+
directions and does not). Whether one array was shared is decided after the
108+
exchange by comparing where the two arrays begin (`host_address_of`).
109+
110+
What was measured (Python 3.12, NumPy 2.5.4, torch 2.14.1 CPU, JAX 0.11.2,
111+
TensorFlow 2.21.0 CPU; pointers, `np.shares_memory` and writing to one array
112+
and reading the other):
113+
114+
| Exchange on the host | Result |
115+
|---|---|
116+
| NumPy to torch | shared, for every dtype tried, Fortran order, stepped and offset views, read-only arrays. A view with a negative step is copied (arraybridge makes it contiguous first). |
117+
| torch to NumPy | shared |
118+
| JAX to NumPy | shared (the NumPy array is read-only) |
119+
| NumPy to JAX | copied, unless the buffer is C-contiguous, starts on a 64-byte boundary and keeps its dtype; then shared |
120+
| NumPy to TensorFlow, TensorFlow to NumPy | copied |
121+
| an array with no elements | nothing to share: `"host copy"` of 0 bytes |
122+
123+
**What `planned` returns when sharing depends on the array.** A plan sees
124+
only declarations and devices, never an array. It returns the route that is
125+
tried first: `SharedHostBuffer` for NumPy, torch and JAX with NumPy on the
126+
host. The record names what was done. Where the exchange copied (NumPy to JAX
127+
for an ordinary NumPy allocation, a reversed view to torch) the record's
128+
mechanism is `"host copy"` and `declined_mechanisms` is
129+
`("shared host buffer",)`, the way a declined DLPack exchange is already
130+
reported. The exchange is done once either way.
131+
132+
What a consumer that keyed on the old answers sees:
133+
134+
- `planned(...) is DeviceMove` is no longer true for the same library and
135+
device; test `is StaysInPlace` (or `route.writes_a_record`).
136+
- Rows that were `"host copy"` for NumPy and torch on the host, and for JAX
137+
to NumPy on the host, are now `"shared host buffer"`. `"host copy"` rows
138+
that follow a declined `SharedHostBuffer` carry it in `declined_mechanisms`,
139+
which `ConversionCounters` does not key on.
140+
- `planned` for NumPy with torch or JAX on the host (either direction) is
141+
`SharedHostBuffer`. Between torch and JAX on the host it is still `"dlpack"`.
142+
Anything to or from an accelerator, pyclesperanto or TensorFlow is planned
143+
as before.
144+
- The `nbytes` of a `from_numpy` record is the size of the array that was
145+
made (it was the size of the NumPy input; they differ when JAX narrows
146+
float64 to float32).
147+
148+
`ConversionRoute.taken(data, result, source, target)` is new: the route that
149+
names what `convert` did, the route itself unless it says otherwise.
150+
`ArrayLibrary.shares_numpy_buffer_on(device)` and
151+
`ArrayLibrary.host_address_of(data)` are new, as is
152+
`NumpyLibrary.registered()`. `HostCopy` and `SharedHostBuffer` share the new
153+
parent `HostExchange`, which has no mechanism of its own.
154+
`arraybridge.libraries` no longer imports `ConversionObserver`,
155+
`ConversionRecord` and `HostCopy` (they were never exported from it; they are
156+
in `arraybridge.conversion`).
157+
158+
**`ConversionObserver.current` belongs to the context that reads it.** It was
159+
one attribute for the whole process, and `installed()` put back whatever it
160+
had seen on entry: two threads that entered and left in the same order left
161+
the second thread's observer installed for the rest of the process. The hook
162+
is now a `contextvars.ContextVar`.
163+
164+
- `ConversionObserver.current` reads the observer of the running thread or
165+
asyncio task. Assigning to it sets the observer of that context only.
166+
- `observer.install()` makes it the observer of this context and returns the
167+
one it replaced. `with observer.installed():` does so for a block.
168+
- A new thread starts with the default observer, which ignores conversions.
169+
**An observer installed in the main thread no longer sees conversions made
170+
in worker threads.** To observe a thread you start, run it in a copy of your
171+
context: `Thread(target=contextvars.copy_context().run, args=(work,))`, or
172+
`executor.submit(contextvars.copy_context().run, work)`.
173+
- An asyncio task starts with the observer of the code that created it, and
174+
what it installs stays in that task.
175+
- `current` is read on the class (`ConversionObserver.current`). It is no
176+
longer an attribute of an observer instance.
177+
80178
### Not verified on a GPU
81179

82180
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.
181+
CPU wheel on 3.12. The host exchanges in the Conversion section were also run
182+
against the JAX and TensorFlow CPU builds named there. CuPy and pyclesperanto,
183+
every accelerator path of torch, TensorFlow and JAX, and everything else
184+
TensorFlow and JAX do, were exercised only through the fakes in
185+
`tests/fakes.py`. `TESTING.md` has the commands for a GPU machine.
86186

87187
## 0.5.0
88188

‎README.md‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -99,10 +99,13 @@ library does not have.
9999

100100
## Which route a conversion takes
101101

102-
A conversion tries three mechanisms in order: `"device move"` (same library,
103-
other device), `"dlpack"` (the target wraps the source's buffer) and
104-
`"host copy"` (download to NumPy, then upload). `ConversionRoute.planned`
105-
tells which one will be tried first. It reads only the library classes and the
102+
A conversion tries five mechanisms in order: `"stays in place"` (same library
103+
and device: nothing is converted), `"device move"` (same library, other
104+
device), `"dlpack"` (the target wraps the source's buffer),
105+
`"shared host buffer"` (both arrays are in main memory and the result is the
106+
source's own buffer) and `"host copy"` (the values are copied through NumPy).
107+
`ConversionRoute.planned` tells which one will be tried first; the record of
108+
a conversion names the one that was used. It reads only the library classes and the
106109
device values, so it works without the libraries or the hardware:
107110

108111
```python
@@ -115,11 +118,12 @@ gpu = AcceleratorDevice(0)
115118
assert ConversionRoute.planned(torch, gpu, cupy, gpu).mechanism == "dlpack"
116119
assert ConversionRoute.planned(torch, HOST, cupy, gpu).mechanism == "host copy"
117120
assert ConversionRoute.planned(torch, HOST, torch, gpu).mechanism == "device move"
121+
assert ConversionRoute.planned(torch, gpu, torch, gpu).mechanism == "stays in place"
118122
```
119123

120124
To see what conversions actually ran, install a `ConversionCounters` observer.
121125
It keeps a count, bytes and seconds per source, target and mechanism. This
122-
example needs JAX:
126+
example needs TensorFlow:
123127

124128
```python
125129
import numpy as np
@@ -128,16 +132,18 @@ from arraybridge import HOST, ConversionCounters, convert_memory
128132

129133
counters = ConversionCounters()
130134
with counters.installed():
131-
convert_memory(np.zeros((4, 4), dtype=np.float32), "numpy", "jax", HOST)
135+
convert_memory(np.zeros((4, 4), dtype=np.float32), "numpy", "tensorflow", HOST)
132136

133137
row = counters.rows()[0]
134-
assert (row["source_library"], row["target_library"]) == ("numpy", "jax")
138+
assert (row["source_library"], row["target_library"]) == ("numpy", "tensorflow")
135139
assert (row["mechanism"], row["count"], row["nbytes"]) == ("host copy", 1, 64)
136140
print(counters.format_table())
137141
```
138142

139-
A call that returns its input unchanged is not counted. With no observer
140-
installed nothing is timed.
143+
A conversion that stays in place is not counted. With no observer installed
144+
nothing is timed. An observer belongs to the thread or asyncio task that
145+
installed it; a thread you start is observed when you run it in a copy of your
146+
context (`contextvars.copy_context().run`).
141147

142148
## Array operations in the array's own library
143149

‎docs/source/api_reference.rst‎

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -138,22 +138,35 @@ Conversion reporting
138138

139139
``ConversionRoute`` has one subclass per mechanism, tried in this order:
140140

141+
``StaysInPlace`` (``"stays in place"``)
142+
Same library and same device. The input is returned and no record is
143+
written (``writes_a_record`` is ``False`` for this route only).
144+
141145
``DeviceMove`` (``"device move"``)
142146
Source and target are the same library; the array changes device only.
143147

144148
``DLPackExchange`` (``"dlpack"``)
145149
The target wraps the source's buffer. Applies when the target imports
146150
DLPack from the source's device and the source exports from it.
147151

152+
``SharedHostBuffer`` (``"shared host buffer"``)
153+
Both arrays are in main memory and the result begins at the address of the
154+
source: no bytes are copied. Applies when both libraries are
155+
``NumpyBufferSharing`` (NumPy, torch, JAX) and both devices are the host.
156+
Whether one array is shared is known after the exchange; one that was
157+
copied is recorded as ``"host copy"`` with ``"shared host buffer"`` under
158+
``declined_mechanisms``.
159+
148160
``HostCopy`` (``"host copy"``)
149-
Download to a NumPy array, then upload to the target. Always applies.
161+
The values are copied through a NumPy array. Always applies.
150162

151163
``ConversionRoute.planned(source_library, source_device, target_library,
152164
target_device)`` returns the route class that a conversion of that pair tries
153165
first. It reads only the library classes and the device values: no library is
154166
imported and no device is touched. The conversion selects its route with the
155167
same test. A route that applies but cannot carry a particular array is
156-
skipped and the next one is tried.
168+
skipped and the next one is tried, so the record of a conversion, not the
169+
plan, says what was done to that array.
157170

158171
.. code-block:: python
159172
@@ -166,19 +179,21 @@ skipped and the next one is tried.
166179
167180
assert ConversionRoute.planned(torch, gpu, cupy, gpu).mechanism == "dlpack"
168181
assert ConversionRoute.planned(torch, HOST, cupy, gpu).mechanism == "host copy"
169-
assert ConversionRoute.planned(numpy_library, HOST, torch, HOST).mechanism == "host copy"
182+
assert ConversionRoute.planned(numpy_library, HOST, torch, HOST).mechanism == "shared host buffer"
183+
assert ConversionRoute.planned(torch, gpu, torch, gpu).mechanism == "stays in place"
170184
assert ConversionRoute.planned(torch, HOST, torch, gpu).mechanism == "device move"
171185
172186
``ConversionObserver``
173187
Receives one ``ConversionRecord`` per conversion while it is installed.
174188
Subclass it and define ``record(record)``. ``observer.install()`` makes it
175-
the process's observer and returns the one it replaced;
176-
``with observer.installed():`` does so for a block.
177-
``ConversionObserver.current`` is the installed observer. The default
189+
the observer of the running thread or asyncio task and returns the one it
190+
replaced; ``with observer.installed():`` does so for a block.
191+
``ConversionObserver.current`` is the observer of the context that reads
192+
it (a ``contextvars.ContextVar``). A new thread starts with the default;
193+
run it with ``contextvars.copy_context().run`` to give it yours. The default
178194
ignores conversions, and then nothing is timed. ``library.convert_to``
179195
(which ``convert_memory`` calls), ``library.to_numpy`` and
180-
``library.from_numpy`` report. A call that returns its input unchanged does
181-
not.
196+
``library.from_numpy`` report. A conversion that stays in place does not.
182197

183198
``ConversionRecord``
184199
Fields: ``source_library``, ``source_device``, ``target_library``,

‎docs/source/converters.rst‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,11 @@ answers about them.
4545
Routes
4646
------
4747

48-
A conversion tries, in order: a device move when source and target are the
49-
same library; a DLPack exchange when the target can wrap the source's buffer
50-
on its device; a copy through a NumPy array in main memory.
48+
A conversion tries, in order: nothing at all when source and target are the
49+
same library on the same device; a device move when they are the same library;
50+
a DLPack exchange when the target can wrap the source's buffer on its device;
51+
an exchange through NumPy in main memory, which shares the buffer where both
52+
libraries can (NumPy, torch, JAX) and copies otherwise.
5153
``ConversionRoute.planned`` tells which is tried first for a pair, and a
5254
``ConversionObserver`` receives what actually ran; both are described in
5355
:doc:`api_reference`. No pair is promised to be zero-copy.

0 commit comments

Comments
 (0)