Repository navigation
Honor reference return policies for JAX CPU arrays - #1468
1akashkalita wants to merge 2 commits into
Conversation
|
At first glance, it seems to me that you're trying to do something that JAX is not intended to support. |
|
The use case is handing a read-only CPU buffer to JAX without allocating a second buffer. Neither the binding nor the test modifies the data after export. The test checks whether the two arrays share storage. JAX exposes this distinction through |
Then why do you care if JAX chooses to make a copy? The C++ code can read from its copy, and JAX can read from its copy, and since both copies are immutable, everybody always reads the same values. Whether JAX does or not make a copy is an optimization decision that can change from one release of JAX to the next, because, philosophically, functions are pure. It can even change based on the CPU. (I'm not saying it does, just that it can. Hypothetically, arm64 could have a bigger performance penalty for unaligned reads than x86_64 has. So, JAX might have different heuristics regarding when to make a copy based on the hardware.) I don't see that it's useful for nanobind to check whether the two arrays share storage and raise an exception if they do not. These exceptions might occur unpredictably. JAX could (theoretically) do something like garbage collection and copy its live arrays to somewhere else when memory usage gets high for the purpose of memory compaction. Suppose my C++ program has, at top-level, When I write Also, I don't want my bindings to become slower by testing whether the two arrays share storage. |
|
The static-buffer example makes the compatibility concern clear. Under that interpretation of |
A CPU binding returning
nb::ndarray<nb::jax, ...>withrv_policy::referencecan return a detached JAX array. For example, passing four floats starting one element past a 64-byte boundary succeeded on JAX 0.12.1, butnp.shares_memory(np.asarray(result), input)was false.Request zero-copy DLPack import for explicit CPU reference policies on JAX versions that accept the keyword. Check that nonempty results share the source buffer because JAX 0.6.2 accepts
copy=Falseand can still allocate an aligned copy. On JAX 0.4.26 the legacy API can share the unaligned buffer directly.The regression test covers aligned, empty, and unaligned inputs. The unaligned case accepts a shared view or an explicit refusal to copy.
Tested on arm64 macOS with the JAX and ndarray test modules.