Alex-PLACET opened a new pull request, #55951:
URL: https://github.com/apache/arrow/pull/55951
### Rationale for this change
Custom per-element logic on Arrow data has no good path from Python today:
`pyarrow.compute` only offers the existing kernels, `to_numpy()` + Numba copies
nullable arrays, drops the validity bitmap and does not handle strings, and
plain Python loops are orders of magnitude slower.
This PR lets `@numba.njit` functions read Arrow arrays without copying and
build new Arrow arrays, returned to Python as `pa.Array`.
### What changes are included in this PR?
- `@njit` functions accept `pa.Array` and Arrow PyCapsule producers
(`__arrow_c_array__`, single-chunk `__arrow_c_stream__`), via
`register_producer(cls)` or `from_any(obj)`.
- Builders for the fixed-width types and
string/large_string/binary/large_binary: `append`, `reserve`, `finish`.
- Later PRs: ChunkedArray/Table/RecordBatch, bulk appends, boolean
reductions, native argument borrowing.
**Reading**
- One Numba type per (Arrow type, may-have-nulls): a dense array compiles
with no null test.
- The data model is the C data interface `ArrowArray` struct, by value, no
pyarrow object is touched in compiled code.
- Unboxing: one Python call per argument (`_capsule.take_array_into`) moves
the producer's struct in, the unbox cleanup calls its `release` when the call
returns.
- `a[i]` is `Optional[T]` for fixed width, a non-allocating `StringView` for
string/binary, an exact `(high, low)` pair for decimal128.
- Unsupported types (nested, dictionary, decimal256) raise `TypeError` at
typing time. Returning an argument array raises at compile time, since its
buffers are released on return.
**Building**
- Buffers are Arrow `PoolBuffer`s allocated in C++. Appends are inlined LLVM
that call into C++ only to grow.
- `finish()` hands the buffers to `PyArrow_MakeAndExportArray`, which
validates them against type and length and exports an `ArrowArray`; the builder
is then spent (`RuntimeError` on further use).
- The result is imported with `pa.Array._import_from_c`, without a copy. A
built array can be returned to Python once, a second return raises
`RuntimeError`.
**C++**
- `libarrow`: an `ExportArray(std::shared_ptr<ArrayData>, ...)` overload in
`arrow/c/bridge.h`, to export a built `ArrayData` without wrapping it in an
`Array`.
- `libarrow_python`: `arrow/python/numba.{h,cc}`, a small `extern "C"` API
(pool buffer alloc/reserve/resize/destroy, make-and-export, release) called
from compiled code.
**Packaging and benchmarks**
- Registered through Numba's `numba_extensions` entry point; `import
pyarrow` never imports Numba.
New files:
- `__init__.py`: the public API and user documentation
- `_capsule.py`: Arrow C data interface in ctypes, run in Python before each
call
- `_utils.py`: shared pieces
- `array.py`: reading arrays
- `builder_types.py`: builder classes and typing, no code generation
- `builder.py`: builder code generation
- `poolbuffer.py`: growable buffers on Arrow's memory pool
### Are these changes tested?
New test files:
- `test_numba.py`
- `test_numba_builder.py`
- `test_numba_capsule.py`
- `test_numba_helpers.py`
- `python/benchmarks/numba*.py`: asv suites (per-type reads and builds,
per-primitive costs, call overhead).
#### Some numbers
##### Input data
- **Per-type arrays:** `pa.array(values(type))`, with every third element
null.
- integers and floats: `i % 100`;
- strings: `b"abcdefgh"[: i % 8 + 1]`;
- bool: `i % 2 == 0`;
- decimal128: `(i % 10000) / 100`.
- **`nullable_ints()`:** int64 `0..N`, with every third element null.
- **`dense_ints()`:** int64 `0..N`, with no validity bitmap.
- **`strings()`:** `b"abcdefgh"`, with every third element null.
##### Reads
**Numba:** a compiled loop reads every element. The numeric case looks like
this:
```python
@nb.njit
def scan(a):
total = 0
nulls = 0
for i in range(len(a)):
if a[i] is None:
nulls += 1
else:
total += a[i]
return total, nulls
```
The other loops follow the same pattern:
| Workload | Numba loop body | PyArrow equivalent |
|---|---|---|
| Integers, floats | sum of non-null values plus null count (above) |
`pc.sum(a)`, `a.null_count` |
| Temporal types | same as integers, on the storage integer |
`pc.sum(a.view(storage type))` |
| decimal128 | `total += decimal_to_float(a[i], 2)` | `pc.sum(a)` (exact
decimal) |
| String, binary, fixed-size binary | `if v.valid: n += string_len(v)` |
`pc.sum(pc.binary_length(a))` |
| bool | count of true values | `pc.sum(a)` |
| `is_valid` | `if is_valid(a, i): acc += a[i]` | `pc.sum(a)` |
| int64, no nulls | the numeric loop on `dense_ints()` | `pc.sum(a)` |
##### Builds
**Numba:** a compiled loop appends every value to a builder, then calls
`finish()`. The fixed-width case looks like this:
```python
@nb.njit
def build(n):
b = apn.Int64Builder() # or any other builder type
b.reserve(n)
for i in range(n):
if i % 3:
b.append(i)
else:
b.append(None)
return b.finish()
```
| Benchmark | Numba loop body | PyArrow from list |
|---|---|---|
| Fixed-width types, 1/3 nulls | `append(i)` / `append(None)` | `pa.array([v
if i % 3 else None ...], type)` |
| bool, 1/3 nulls | `append(i % 2 == 0)` / `append(None)` | `pa.array([...],
pa.bool_())` |
| String and binary types, 1/3 nulls | `append(b"abcdefgh")` /
`append(None)` | `pa.array([...], type)` |
| `append(i % 100)`, reserved | Int64Builder | `pa.array([i % 100 ...])` |
| `append(None)` | Int64Builder | `pa.array([None] * N, pa.int64())` |
| `append(i % 3 == 0)` | BoolBuilder | `pa.array([...])` |
| `append(b"abcdefgh")` | StringBuilder, no nulls | `pa.array([B] * N,
pa.string())` |
| Copy a string column | `b.append(source[i])` | `pa.array(src.to_pylist())`
|
####€ Cold and warm calls
The per-type read and build loops are timed three ways, each case in a fresh
process:
| Measure | What it includes |
|---|---|
| Cold | First call of a new `@njit` function: typing, LLVM compilation, one
run |
| Cached | First call in a new process with `@njit(cache=True)`, the code
loaded from Numba's disk cache |
| Warm | Median of the next 15 calls (what every other table reports) |
##### Results
**Setup:** N = 1,048,576 values; median of 15 runs; pinned to a single core
of an i7-13700H; Python 3.13.16, numba 0.68.1, numpy 2.5.4; Arrow C++ built
from the same `main` (SSE4.2 baseline, AVX2 chosen at runtime).
### Reads: PyArrow compute kernel vs Numba
| Type | PyArrow | Numba cold | Numba cached | Numba warm | PyArrow / cold |
PyArrow / cached | PyArrow / warm |
|---|---|---|---|---|---|---|---|
| int8 | 1.34 ms | 384 ms | 81 ms | 0.52 ms | 0.003x | 0.016x | **2.60x** |
| int16 | 1.35 ms | 385 ms | 81 ms | 0.52 ms | 0.003x | 0.017x | **2.61x** |
| int32 | 1.46 ms | 386 ms | 80 ms | 0.93 ms | 0.004x | 0.018x | **1.57x** |
| int64 | 1.25 ms | 383 ms | 82 ms | 0.81 ms | 0.003x | 0.015x | **1.54x** |
| uint8 | 1.37 ms | 391 ms | 82 ms | 0.52 ms | 0.004x | 0.017x | **2.64x** |
| uint16 | 1.44 ms | 384 ms | 79 ms | 0.52 ms | 0.004x | 0.018x | **2.78x** |
| uint32 | 1.43 ms | 384 ms | 82 ms | 0.93 ms | 0.004x | 0.017x | **1.53x** |
| uint64 | 1.26 ms | 386 ms | 82 ms | 0.80 ms | 0.003x | 0.015x | **1.58x** |
| float32 | 1.93 ms | 384 ms | 84 ms | 0.66 ms | 0.005x | 0.023x | **2.94x**
|
| float64 | 1.75 ms | 385 ms | 81 ms | 0.54 ms | 0.005x | 0.022x | **3.26x**
|
| date32 | 1.48 ms | 391 ms | 86 ms | 0.89 ms | 0.004x | 0.017x | **1.67x** |
| date64 | 1.26 ms | 416 ms | 82 ms | 0.84 ms | 0.003x | 0.015x | **1.50x** |
| time32_s | 1.46 ms | 385 ms | 81 ms | 0.88 ms | 0.004x | 0.018x |
**1.66x** |
| time64_us | 1.27 ms | 388 ms | 82 ms | 0.84 ms | 0.003x | 0.015x |
**1.51x** |
| timestamp_us | 1.26 ms | 381 ms | 82 ms | 0.83 ms | 0.003x | 0.015x |
**1.52x** |
| duration_s | 1.25 ms | 385 ms | 83 ms | 0.80 ms | 0.003x | 0.015x |
**1.57x** |
| decimal128 | 1.84 ms | 452 ms | 81 ms | 0.95 ms | 0.004x | 0.023x |
**1.93x** |
| bool | 0.02 ms | 407 ms | 84 ms | 0.54 ms | 0.000x | 0.000x | **0.03x** |
| string | 2.26 ms | 336 ms | 81 ms | 0.54 ms | 0.007x | 0.028x | **4.16x** |
| large_string | 2.11 ms | 341 ms | 81 ms | 1.11 ms | 0.006x | 0.026x |
**1.90x** |
| binary | 2.26 ms | 339 ms | 80 ms | 0.54 ms | 0.007x | 0.028x | **4.17x** |
| large_binary | 2.10 ms | 335 ms | 82 ms | 1.11 ms | 0.006x | 0.026x |
**1.89x** |
| fixed_size_binary | 1.57 ms | 334 ms | 81 ms | 0.46 ms | 0.005x | 0.019x |
**3.45x** |
- **bool:** the Numba loop reads one element at a time, Arrow counts whole
bitmap words. It will be fixed in another PR
-
### Builds: PyArrow vs Numba builder
PyArrow builds the same array from a Python list: a Python loop computes the
values, then `pa.array(list, type)` converts them.
| Type | PyArrow from list | Numba cold | Numba cached | Numba warm |
PyArrow / cold | PyArrow / cached | PyArrow / warm |
|---|---|---|---|---|---|---|---|
| int8 | 61 ms | 275 ms | 87 ms | 1.58 ms | 0.221x | 0.698x | **38.33x** |
| int16 | 70 ms | 273 ms | 83 ms | 1.58 ms | 0.257x | 0.840x | **44.34x** |
| int32 | 70 ms | 281 ms | 84 ms | 1.60 ms | 0.248x | 0.832x | **43.60x** |
| int64 | 71 ms | 277 ms | 83 ms | 1.59 ms | 0.256x | 0.855x | **44.41x** |
| uint8 | 53 ms | 274 ms | 83 ms | 1.59 ms | 0.192x | 0.632x | **33.22x** |
| uint16 | 70 ms | 278 ms | 83 ms | 1.58 ms | 0.250x | 0.839x | **43.97x** |
| uint32 | 71 ms | 275 ms | 84 ms | 1.59 ms | 0.257x | 0.847x | **44.38x** |
| uint64 | 71 ms | 276 ms | 83 ms | 1.59 ms | 0.258x | 0.857x | **44.66x** |
| float32 | 69 ms | 276 ms | 82 ms | 1.59 ms | 0.251x | 0.841x | **43.44x** |
| float64 | 64 ms | 279 ms | 82 ms | 1.57 ms | 0.231x | 0.782x | **41.09x** |
| bool | 41 ms | 286 ms | 85 ms | 2.27 ms | 0.143x | 0.486x | **18.07x** |
| string | 50 ms | 378 ms | 86 ms | 2.28 ms | 0.132x | 0.579x | **21.95x** |
| large_string | 50 ms | 377 ms | 83 ms | 2.34 ms | 0.132x | 0.597x |
**21.22x** |
| binary | 38 ms | 384 ms | 97 ms | 2.55 ms | 0.098x | 0.387x | **14.77x** |
| large_binary | 39 ms | 386 ms | 86 ms | 2.51 ms | 0.102x | 0.461x |
**15.72x** |
### Are there any user-facing changes?
A new optional module, `pyarrow.numba`, available when Numba is installed.
No change to existing APIs.
### Was AI used for this PR?
In accordance to the [AI generation
guidelines](https://arrow.apache.org/docs/dev/developers/overview.html#ai-generated-code),
please disclose below whether and how AI was used in this PR.
**PR code and description written by:**
- [x] Human
- [x] AI
**Reviewed before submission by:**
- [x] Human
- [x] AI
- [ ] Not reviewed
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]