Skip to content

ENH: Convert four self-contained multiarray types to heap types - #32552

Open
prathamhole14 wants to merge 5 commits into
numpy:mainfrom
prathamhole14:heap_types_batch_b
Open

prathamhole14 wants to merge 5 commits into
numpy:mainfrom
prathamhole14:heap_types_batch_b

Conversation

@prathamhole14

@prathamhole14 prathamhole14 commented Sep 9, 2026 •

Copy link
Copy Markdown
Member

PR summary

Related to: #31913, #32451 and #32747

To be merged after #32502

AI Disclosure

Since this is similar to what I did for heap type a PR (#32502), I asked claude opus 5 extra high to make similar changes and corrected at the places where it made wrong decisions. Verified everything myself.

@mattip

mattip commented Sep 14, 2026

Copy link
Copy Markdown
Member

This has conflicts, but overall looks good. Are any of these types involved in hot paths that might affect performance? Although I would think the result would be mixed since the changes will cause rearrangement of memory layout, some will speed things up, some will slow them down.

@prathamhole14
prathamhole14 force-pushed the heap_types_batch_b branch 2 times, most recently from 0954a2a to 1a1b89b Compare September 15, 2026 06:32
@prathamhole14

Copy link
Copy Markdown
Member Author

The per-call overhead is minimal as ArrayMethod and BoundArrayMethod are cached at registration (adding only a single _npy_module_state load to PyObject_TypeCheck) while other iterators and minmax are init-time only. The only component created per advanced-indexing call is MapIter which handles its own type incref/decref.

This has conflicts, but overall looks good. Are any of these types involved in hot paths that might affect performance? Although I would think the result would be mixed since the changes will cause rearrangement of memory layout, some will speed things up, some will slow them down.

@mattip

mattip commented Sep 22, 2026

Copy link
Copy Markdown
Member

LGTM. None of these types are public API, so I think this is clean. Anyone else want to take a look?

@ngoldbaum

Copy link
Copy Markdown
Member

Unfortunately I think there's a multithreaded scaling problem that gets introduced here. I used an AI model to generate this code and this benchmark is something of a worse-case scenario. Still, I think it bears thinking about for this work.

Put these three files together outside NumPy’s source tree. Use free-threaded Python with the NumPy build you want to test installed, plus a C compiler (Linux/macOS).

iterbench.c

#include <Python.h>
#include <numpy/arrayobject.h>

static PyObject *run(PyObject *self, PyObject *args) {
    PyArrayObject *a;
    Py_ssize_t count;
    if (!PyArg_ParseTuple(args, "O!n", &PyArray_Type, &a, &count)) return NULL;
    if (PyArray_NDIM(a) != 1 || PyArray_SIZE(a) == 0) {
        PyErr_SetString(PyExc_ValueError, "expected a nonempty 1D array");
        return NULL;
    }
    PyArrayIterObject *it = (PyArrayIterObject *)PyArray_IterNew((PyObject *)a);
    if (it == NULL) return NULL;
    npy_intp bounds[] = {-1, 1};
    for (Py_ssize_t i = 0; i < count; i++) {
        PyObject *n = PyArray_NeighborhoodIterNew(
            it, bounds, NPY_NEIGHBORHOOD_ITER_CIRCULAR_PADDING, NULL);
        if (n == NULL) { Py_DECREF(it); return NULL; }
        Py_DECREF(n);
    }
    Py_DECREF(it);
    Py_RETURN_NONE;
}

static PyMethodDef methods[] = {
    {"run", run, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL}
};
static struct PyModuleDef module = {
    PyModuleDef_HEAD_INIT, "_iterbench", NULL, -1, methods
};
PyMODINIT_FUNC PyInit__iterbench(void) {
    import_array();
    PyObject *m = PyModule_Create(&module);
#ifdef Py_GIL_DISABLED
    if (m != NULL) PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED);
#endif
    return m;
}

setup.py

from setuptools import Extension, setup
import numpy as np

setup(
    name="iterbench",
    version="0.0.0",
    ext_modules=[Extension(
        "_iterbench", ["iterbench.c"],
        include_dirs=[np.get_include()],
        extra_compile_args=["-O2", "-std=c11"],
    )],
)

bench.py

import sys
from concurrent.futures import ThreadPoolExecutor
from statistics import median
from time import perf_counter
import numpy as np
import _iterbench

assert not sys._is_gil_enabled(), "Requires free-threaded Python, GIL disabled"

def work(_):
    _iterbench.run(np.arange(5.), 1_000_000)

for threads in (1, 4, 8):
    times = []
    with ThreadPoolExecutor(threads) as pool:
        for repeat in range(3):
            start = perf_counter()
            list(pool.map(work, range(threads)))
            times.append(perf_counter() - start)
    print(f"{threads} threads: {threads / median(times):.1f} million iterators/s")

Build and run

python3.14t -m pip install setuptools
python3.14t setup.py build_ext --inplace
python3.14t bench.py

Results

Before the PR:

1 threads: 23.0 million iterators/s
4 threads: 83.8 million iterators/s
8 threads: 106.8 million iterators/s

With the PR:

1 threads: 26.7 million iterators/s
4 threads: 11.7 million iterators/s
8 threads: 5.7 million iterators/s

Since there's no public API to make heap types immortal and because the increfs and decrefs generating the contention are coming from creating iterator objects and can't be eliminated outside the interpreter (an instance has a reference to its type).

I guess this is just further argument that it would be nice to make heap types immortal. @kumaraditya303 FYI.

@ikrommyd

Copy link
Copy Markdown
Member

Nathan could there also be free threading issues like this with previous types that were converted to heap types, e.g. in #32502 for example?

@prathamhole14

Copy link
Copy Markdown
Member Author

I measured the #32502 types on 3.14t. Yes flagsobj has the same problem -- a.flags in a tight loop goes from 153 to 19.5 M calls/s at 8 threads and _array_converter uses the same pattern.

np.require and np.broadcast_arrays are 5-12% slower at 4-8 threads, and linspace and delete show no change.

We can fix this directly in Numpy. The bottleneck is Py_DECREF(type) in our custom tp_dealloc. If we drop tp_dealloc, CPython defaults to subtype_dealloc, which uses much faster per-thread refcounting. We'd just move our cleanup code to tp_free (our DType classes already do this).

In an 8-thread test, this bumped performance from ~40M to 173M objects/s. The only trade-off is a tiny ~3ns overhead on GIL builds.

Would you be okay with this? If yes then I will open a follow-up PR for the #32502 types and use the same pattern in this PR.

@mattip

mattip commented Sep 30, 2026

Copy link
Copy Markdown
Member

Nice. That handles the case of the free-threading build mentioned by @ngoldbaum, and also removes the custom tp_dealloc

@prathamhole14

Copy link
Copy Markdown
Member Author

@mattip and @ngoldbaum I updated this PR with the same change as #32853, the four types here no longer define tp_dealloc. With your neighborhood iterator benchmark on 3.14t.

  • 8 threads go from 26.7 to 79.5 M iterators/s and 4 threads from 30.9 to 58.2.

On a GIL build it costs about 9 ns per iterator, and advanced indexing (MapIter) shows no measurable change.

@prathamhole14

Copy link
Copy Markdown
Member Author

Lets merge this then and once the CPython PR is merged python/cpython#160138, I will open one new PR that makes all the per-call heap types immortal for both the #32502 types and the #32552 types. I think @seberg is suggesting the same -- #32853 (comment)

@ngoldbaum

Copy link
Copy Markdown
Member

I think merging with main will fix the circleci failure.

Is there a way forward for you elsewhere without temporarily introducing new free-threaded scaling regressions?

@prathamhole14

Copy link
Copy Markdown
Member Author

Yes @ngoldbaum
We have some options:

  1. static only on free-threaded builds, heap types everywhere else
  2. dropping tp_dealloc workaround (this change was reverted earlier as @seberg suggested ref: ENH: Reduce refcount contention on heap types in free-threaded builds #32853)
    I would personally go with dropping tp_dealloc option

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants