Skip to content

ENH: ufunc.at: call the inner loop once per subarray when casting - #3

Open
cakedev0 wants to merge 1 commit into
ufunc-at-rowsfrom
ufunc-at-rows-cast
Open

cakedev0 wants to merge 1 commit into
ufunc-at-rowsfrom
ufunc-at-rows-cast

Conversation

@cakedev0

@cakedev0 cakedev0 commented Nov 13, 2026 •

Copy link
Copy Markdown
Owner

Stacked on numpy#33326 (branch ufunc-at-rows), which calls the inner loop once per run of the last dimension when the indices select subarrays and no cast is needed. This does the same when an operand needs a cast, has a non-native byte order or is not aligned.

What changes

ufunc_at__slow_iter handles those cases with a buffered NpyIter over dummy one-element operands: for every element it resets the base pointers (cast into the buffers), calls the loop with count=1, and calls iternext (cast back).

It now takes a run argument. When run > 1:

  • the dummy operands are 1-D arrays of run elements with the real strides, so one reset casts a whole run;
  • the inner loop is called in a do/while on iternext, since a run longer than the buffer is split into chunks;
  • the loop is fetched again with the fixed strides of the iterator, as execute_ufunc_loop does. The loop passed by the caller is the contiguous one, which was only valid because count was 1;
  • the map iterator is advanced by run, as in ufunc_at__subspace_iter.

With run == 1 the path is the same as before, except that the iterator is created with NPY_CORDER instead of NPY_KEEPORDER (no effect on one element, avoids flipping negative strides for a run).

The condition for iterating by runs moved out of the no-cast branch so both paths share it.

Benchmark

np.add.at(sums, labels, rows), 16384 rows, 256 labels, 200 columns unless stated. Best of 7, 3 interleaved rounds, one pinned core of a Core Ultra X7 358H. "Before" is the numpy#33326 state (a build of 2026-11-10 in a different Python environment).

case before after
f4 += f4 (no cast, control) 0.50 ms 0.50 ms
f8 += f4 92 ms 1.25 ms
f4 += f8 103 ms 2.05 ms
f8 += i4 91 ms 1.35 ms
f8 += f4, 8 columns 3.8 ms 0.63 ms
f8 += f4, 2 columns 1.03 ms 0.59 ms

Checks

Not done: release note, and the asv benchmark time_sum_at_rows_cast was added but not run through asv.

🤖 Generated with Claude Code

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant