← Back to Pull requests

ENH: Convert flatiter, broadcast and nditer to heap types #32641

Open
prathamhole14 opened this pull request with 273 lines diff across 11 files
View on GitHub
prathamhole14 prathamhole14 commented on Sep 15, 2026 18:44 UTC
Author

PR summary


<!-- Please take some time to make it easier for us to review
your pull request (PR). Describe the PR using the questions below as guidance.

  • What problem does this PR solve? Link any relevant issues and PRs.

  • Why are you interested in working on this PR?

  • How does the proposed change help you?
  • Please keep in mind that even seemingly small changes can have unexpected consequences
    for workflows unrelated to the ones you may be familiar with. For this reason, maintainers
    carefully consider the risks of all changes, including bug fixes.

    Make sure to review the guidelines for contributing code to NumPy and fill out the AI disclosure section below.

    Please note that non-maintainers may only have 2 non-draft PRs open for review at a
    time.

    -->
    Related to: https://github.com/numpy/numpy/issues/31913 as part of adaptation of LIMITED API for _multiarray_umath module
    Also related to: https://github.com/numpy/numpy/issues/32451 and https://github.com/numpy/numpy/issues/32747

    AI Disclosure


    <!-- If AI was used in the preparation of this PR, please disclose
    the tool(s) used, how they were used, and specify what code or text is AI generated.
    If no AI tools were used, please write "No AI tools used" in this section.

    All interactions with reviewers must be performed by humans, including the submission of PRs.

    Read the NumPy policy on AI generated code at https://numpy.org/devdocs/dev/ai_policy.html.

    -->
    Ported nditer myself and after getting idea of it (and other changes are almost similar) and mechanical used claude opus 5 extra high to convert to heap type, and verified the code changes myself.

    Diff: 273 lines (+188 / -85) across 11 files Reviewer: mattip Review duration: 115224m
    All Vouch review confidence checks passed
    Residual risk 0.06 = Change Risk (0.58) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.58 · 273 lines diff across 11 files
    0.58
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.90 · 5 substantive comment(s)
    0.90
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    89%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.336
    Real PR Conversation Timeline
    13 items
    prathamhole14 prathamhole14 commented on Sep 16, 2026 04:45 UTC
    Author

    Ready for review.

    mattip mattip commented on code on Sep 16, 2026 05:22 UTC
    Code Review
    numpy/_core/src/multiarray/iterators.c:1
    @@ -1093,21 +1090,43 @@ static PyGetSetDef iter_getsets[] = {
         {NULL, NULL, NULL, NULL, NULL},
     };
     
    -NPY_NO_EXPORT PyTypeObject PyArrayIter_Type = {
    -    PyVarObject_HEAD_INIT(NULL, 0)
    -    .tp_name = "numpy.flatiter",
    -    .tp_basicsize = sizeof(PyArrayIterObject),
    -    .tp_dealloc = (destructor)arrayiter_dealloc,
    -    .tp_free = PyObject_Free,
    -    .tp_as_mapping = &iter_as_mapping,
    -    .tp_flags = Py_TPFLAGS_DEFAULT,
    -    .tp_richcompare = (richcmpfunc)iter_richcompare,
    -    .tp_iternext = (iternextfunc)arrayiter_next,
    -    .tp_methods = iter_methods,
    -    .tp_members = iter_members,
    -    .tp_getset = iter_getsets,
    +static PyType_Slot arrayiter_slots[] = {
    +    {Py_tp_dealloc, arrayiter_dealloc},
    +    {Py_mp_length, iter_length},
    +    {Py_mp_subscript, iter_subscript},
    +    {Py_mp_ass_subscript, iter_ass_subscript},
    +    {Py_tp_richcompare, iter_richcompare},
    +    {Py_tp_iter, PyObject_SelfIter},
    +    {Py_tp_iternext, arrayiter_next},
    +    {Py_tp_methods, iter_methods},
    +    {Py_tp_members, iter_members},
    +    {Py_tp_getset, iter_getsets},
    +    {0, NULL},
    +};
    +
    +/*
    + * `PyType_Ready` gave the static type `Py_TPFLAGS_DISALLOW_INSTANTIATION`
    + * because it had no `tp_new`; a heap type would inherit `object.__new__`.
    + */

    Does this historical comment add to current understanding of the code.

    mattip mattip commented on code on Sep 16, 2026 05:30 UTC
    Code Review
    numpy/_core/src/multiarray/multiarraymodule.c:1
    @@ -5276,6 +5277,19 @@ multiarray_umath_free(void *m)
     }
     #endif
     
    +/*
    + * Heap types have no compile time address, so the generated `PyArray_API`
    + * initializer leaves their slots NULL.  The public macros still read those
    + * slots, so fill them once the types exist, as `_fill_dtype_api` does.
    + */
    +static void
    +_fill_heap_type_api(void *api_table[], multiarray_umath_state *state)
    +{
    +    api_table[NPY_API_INDEX_PyArrayIter_Type] = state->flatiter_type;
    +    api_table[NPY_API_INDEX_PyArrayMultiIter_Type] = state->broadcast_type;
    +    api_table[NPY_API_INDEX_NpyIter_Type] = state->nditer_type;
    +}
    +

    Since we export these types, and CPython errors when creating static types with heap type base classes, I am not sure we can do this yet.

    prathamhole14 prathamhole14 commented on code on Sep 16, 2026 06:16 UTC
    Code Review
    numpy/_core/src/multiarray/multiarraymodule.c:1
    @@ -5276,6 +5277,19 @@ multiarray_umath_free(void *m)
     }
     #endif
     
    +/*
    + * Heap types have no compile time address, so the generated `PyArray_API`
    + * initializer leaves their slots NULL.  The public macros still read those
    + * slots, so fill them once the types exist, as `_fill_dtype_api` does.
    + */
    +static void
    +_fill_heap_type_api(void *api_table[], multiarray_umath_state *state)
    +{
    +    api_table[NPY_API_INDEX_PyArrayIter_Type] = state->flatiter_type;
    +    api_table[NPY_API_INDEX_PyArrayMultiIter_Type] = state->broadcast_type;
    +    api_table[NPY_API_INDEX_NpyIter_Type] = state->nditer_type;
    +}
    +

    You are right, PyType_Ready rejects it and none of these three set Py_TPFLAGS_BASETYPE and neither does ufunc, so the static C route only ever worked because PyType_Ready skips that check.

    Maybe BASETYPE is the line to draw here. If a type never claimed to be a base, converting it seems correct.
    ndarray, dtype and the scalar types are the real problem and i think they need their own discussion.

    Also does this require release note?
    Edit: I have added release note

    mattip mattip commented on Sep 22, 2026 10:24 UTC
    Contributor

    I don't think we can merge this, since it will break any subclassing of these types with static types.

    ikrommyd ikrommyd commented on Sep 22, 2026 16:20 UTC
    Contributor

    Forgive my ignorance Matti but I was just curious, does numpy subclass those with static types somewhere or are you thinking users might?

    mattip mattip commented on Sep 22, 2026 20:55 UTC
    Contributor

    Users might, since we export them in the API struct.

    prathamhole14 prathamhole14 commented on Sep 23, 2026 03:56 UTC
    Author

    So would like to know which direction is acceptable.

    1. Adding note in this release that static subclassing of these types is unsupported, then convert them a release later.

    2. Heap types only under Py_LIMITED_API, static types otherwise. I know other folks are not fan of #ifdef Py_LIMITED_API as it means two definitions per type but it's confined to the type definition block and normal builds are untouched. This can go along with the release note from point 1 as well and then in later release we can drop non limited one entirely?

    If neither works, then _multiarray_umath can't be built against the Limited API at all, since a static PyTypeObject doesn't compile once Py_LIMITED_API is defined.

    mattip mattip commented on Sep 23, 2026 04:12 UTC
    Contributor

    I think we should discuss this at a community/triage meeting. In the meantime, can you scan popular github projects for code subclassing these types as static (or for that matter, even heap) types?

    prathamhole14 prathamhole14 commented on Sep 23, 2026 18:00 UTC
    Author

    I searched for this and for the types in this PR no project sets tp_base to PyArrayIter_Type, PyArrayMultiIter_Type, NpyIter_Type or PyUFunc_Type. The ones mentioning them almost all are vendored NumPy headers, NumPy forks or CPython itself.

    mattip mattip commented on Sep 23, 2026 18:12 UTC
    Contributor

    We discussed this at the community meeting and the general opinion was positive, the probability that anyone is subclassing these is quite small. I will give this one more review pass.

    mattip mattip commented on Sep 24, 2026 03:44 UTC
    Contributor

    Other than @ngoldbaum's valid analysis on the performance cost of the change to heap types on #32552, I didn't find any problems here. One thing it might be nice to check is that the assignments of the type in PyArray_API succeed. A good test would be to add to _multiarray_tests.c.src a check that only known slots are NULL, since I don't think we have anything today that does a check. There are some slots that should be NULL, so the test would have to take that into consideration.

    Reviewers
    Assignees
    prathamhole14 prathamhole14
    Labels
    risk: low confidence: 89.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 58.2% (MEDIUM) · Higher = larger blast radius
    58.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 89.2% · Lower = rushed or shallow review
    89.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 6.3% · Safe to merge
    6.3%
    Repository