Skip to content

ENH: ufunc.at: call the inner loop once per indexed row (30x speed-up) - #33326

Open
cakedev0 wants to merge 14 commits into
numpy:mainfrom
cakedev0:ufunc-at-rows
Open

cakedev0 wants to merge 14 commits into
numpy:mainfrom
cakedev0:ufunc-at-rows

Conversation

@cakedev0

@cakedev0 cakedev0 commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Story time

to me that's the most important part: it tells why is this change is worth review effort

np.add.at(sums, labels, rows) with a 2-D sums is ~30x slower than it needs to be.

I had hit that several years ago when I was working on a "Hierarchical k-means" algorithm (used to cluster embeddings). The algorithm was not great, but in the process of making it a bit better and faster, I noticed that numpy.add.at was terribly slow in 2D and I wrote a numba kernel to replace it.

Two days ago I've hit that again while benchmarking NumpyEmeans from FAISS. I noticed they replaced it with a SciPy sparse product on main, as they noticed too that numpy.add.at is slow.

PR summary

Context: every ufunc has a C "inner loop" with the signature loop(pointers, count, strides). It processes count elements, moving each pointer by its stride after every element. Calling it has a fixed cost, which is negligible when count is large and dominant when count is 1.

ufunc.at has a special path that avoids calling the loop with count=1 in the 1-D case, by doing a[idx[i]] += b[i] directly. In all other cases, it calls the loop once per element, with count=1.

This can be avoided when the indices select whole rows instead of single elements, i.e. when at least one dimension of the target is taken by a slice rather than an index array (as in np.add.at(sums, labels, rows), where labels picks whole rows of sums), and no cast is needed. In that case, the loop can be called once per run of the last unindexed dimension (a row in the example above), with count=last_dim_size and the real strides, instead of once per element.

This is safe because a run never contains the same element twice. Repeated indices (the reason ufunc.at exists) only occur between different runs, and those are still processed one after the other.

And this makes numpy.add.at as fast as it should be in those cases (~30x faster on my machine)

Detailed benchmarks
import numpy as np

rng = np.random.default_rng(0)
rows = rng.standard_normal((16384, 200), dtype=np.float32)
labels = rng.integers(0, 256, 16384)
sums = np.zeros((256, 201), np.float32)[:, :-1]  # FAISS uses a strided view
np.add.at(sums, labels, rows)

Median times on one P-core of a Core Ultra X7 358H:

B x d, k main this PR SciPy CSC one-hot @ rows
2048 x 200, 256 2.5 ms 0.07 ms 0.09 ms
16384 x 200, 256 17.8 ms 0.55 ms 0.44 ms
16384 x 512, 1024 50.8 ms 1.8 ms 1.9 ms
65536 x 512, 256 202 ms 5.7 ms 5.7 ms

Contiguous or strided sums and float32 or float64 give the same speed-up. One epoch of FAISS 1.16 NumpyEmeans on GloVe-200 (1.18M x 200, k=256, 73 steps, 4 threads) goes from 1.82 s to 0.49 s, with the same objective.

This depends on #33327 (merged), which fixed a bug this change exposed.

Tests:

  • the new test_ufunc_at_rows_and_columns compares against applying the ufunc one index at a time (rows and columns, strided, reversed and transposed targets, broadcast and non-contiguous values)
  • Claude also compared 3,000 random ufunc.at calls (1 to 3 dims, two index arrays, views, 5 ufuncs and 5 dtypes) between main and this branch, with no difference

First time contributor introduction

Not my first PR here (#29837 and #30070, on weighted quantiles), but a short intro anyway: I work on scikit-learn performance (see my recent post on scikit-learn's blog), and I often use AI agents to investigate weird points in the benchmarks I run.
Claude pointed at numpy.add.at and I remembered I had already had troubles with it, so it felt like it was worth digging. I asked Claude to investigate and it came up with this.

AI Disclosure

Claude Opus 5.5 did everything, I've only steered it and reviewed the code, but honestly I don't understand everything in it. I do get the big picture and understand why this is fast. Also I trust Claude to write better code than me (sadly), and most importantly, I trust the tests and the benchmarks (those I can understand).

cakedev0 and others added 2 commits November 12, 2026 13:58
When the output was not contiguous, an input stride equal to the itemsize
in elements (4 for float32, 8 for float64) was taken for a contiguous
input, so `np.negative(a[::4], out=out[::2])` read `a[:4]`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When the indices select subarrays (e.g. `np.add.at(sums, labels, rows)`
with a 2-D `sums`), call the inner loop once per run of the last dimension
instead of once per element.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ikrommyd

Copy link
Copy Markdown
Member

Any chance you can spin off the bug fix into a separate pr and then we can rebase this one? The reason being is that we can put it in 2.6.0 which will be branched off soon and we can also backport it. This pr will take longer to merge than a 1 line bug fix.

When the output was not contiguous, an input stride equal to the itemsize
in elements (4 for float32, 8 for float64) was taken for a contiguous
input, so `np.negative(a[::4], out=out[::2])` read `a[:4]`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cakedev0

Copy link
Copy Markdown
Contributor Author

The fix is now in #33327. I left the fix in this PR too for now because the new ufunc.at path depends on it: it calls the inner loop with the real strides, so np.negative.at on rows of a strided array hits that bug, and test_ufunc_at_subarrays fails without the fix.

@ngoldbaum

ngoldbaum commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Any chance you can re-write the PR summary in your own words? The current summary is very dense, reads claudeish and it's hard for me to understand. I know you're not a native English speaker, feel free to use machine translation of an explanation in your own words.

@cakedev0

Copy link
Copy Markdown
Contributor Author

Fair, I was a bit lazy on this one given that's it's not trivial. I rewrote most of the summary (with some help from Claude).

@cakedev0

Copy link
Copy Markdown
Contributor Author

While thinking a bit more about this PR, it came to my mind that the "slow & cast" path could benefit from the same optimization as what it done in this PR. It's there: cakedev0#3: 50x faster for the cases it speeds up. Let me know if you want this in this PR, in a separate PR or not for now.

@cakedev0 cakedev0 changed the title ENH: ufunc.at: call the inner loop once per subarray ENH: ufunc.at: call the inner loop once per subarray (30x speed-up) Nov 14, 2026
@ikrommyd
ikrommyd self-requested a review November 17, 2026 14:30
@ikrommyd

Copy link
Copy Markdown
Member

I'd say let's converge on this one first and then do a follow-up.

@ngoldbaum

Copy link
Copy Markdown
Member

FYI subarray has a very specific meaning in the NumPy codebase related to the void dtype that I think doesn't correspond to how you're using it in the title here. That threw me off while first looking at it and might have done the same for others. Unless I'm mistaken and you're really excited about performance of void dtype corner cases.

Subarray means a void dtype subarray in NumPy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cakedev0 cakedev0 changed the title ENH: ufunc.at: call the inner loop once per subarray (30x speed-up) ENH: ufunc.at: call the inner loop once per indexed row (30x speed-up) Nov 17, 2026
@cakedev0

Copy link
Copy Markdown
Contributor Author

you're really excited about performance of void dtype corner cases.

Ahah, no indeed I'm not. Claude used subarrays and it made sense for me, I didn't know it was tied to such a corner case ^

Thanks, for the feedback, I renamed it a bit everywhere (title included).

@ngoldbaum
ngoldbaum requested a review from eendebakpt November 18, 2026 14:49
cakedev0 and others added 2 commits November 20, 2026 22:59
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Instead of a separate ufunc_at__subspace_iter, pass the run length and
the strides to ufunc_at__fast_iter. ufunc_at determines both before its
single get_strided_loop call, so the second loop lookup is no longer
needed.
@eendebakpt

Copy link
Copy Markdown
Contributor

The speedup is real and it is a valid use case (although not the most important one I would say). The new ufunc_at__subspace_iter adds and duplicates code though. We may be able to use the existing fast path with a modified strides, e.g. something like main...eendebakpt:numpy:ufunc-at-rows-simplify.

@cakedev0 Could you investigate that approach?

@cakedev0

cakedev0 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

Thank you! Indeed what you propose seems to be less code, I'm looking into it.

not the most important one I would say

Personally, each time I used numpy.add.at on a 2D input would be in this case, but it was indeed rare (And I used numpy a LOT for several years, I think I used the 1d case hundreds of times but with numpy.bincount). IIRC, I encountered a 2D use case 3 times in my life:

  • k-means by groups (the hierarchical k-means from the PR description)
  • sparse SGD on linear models in recommender systems, where a mini-batch only updates the rows of the ids it contains
  • (not me directly but:) the EMeans implementation of FAISS (NumpyEmeans), which replaced np.add.at with a SciPy sparse product because of this slowness.

@cakedev0

Copy link
Copy Markdown
Contributor Author

@cakedev0 Could you investigate that approach?

The tests pass, it's less code / no duplication and it's the same speed 👌 Also, it looks like what Claude did in cakedev0#3 (same optimization but for the "slow-cast" path).

So thanks a lot, I'll use that implementations 👍

Also add the release note.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

@cakedev0 cakedev0 left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't say I understand each line 100%, but I did my best to understand what Claude has to say about it, and I think there is one point worth discussing (see below).

Comment on lines +6445 to +6453
if (count > 1) {
/* move to the last element of the run, to then step past it */
iter->iter_count -= count - 1;
iter->subspace_ptrs[0] += (count - 1) * strides[0];
}
else if (iter2 != NULL) {
PyArray_ITER_NEXT(iter2);
}
PyArray_MapIterNext(iter);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These lines are fragile:

iter->iter_count -= count - 1;
iter->subspace_ptrs[0] += (count - 1) * strides[0];

They are coupled with inner logic of how PyArray_MapIterNext in mapping.c. To get to the next row, this code jumps the iterator to the last element of the row by hand, then calls the normal step: PyArray_MapIterNext(iter);.

A possible change: put the same arithmetic in a small helper next to PyArray_MapIterNext, so that the invariant lives with the iterator. Maybe PyArray_MapIterSkip(PyArrayMapIterObject *mit, npy_intp n), which only does the jump, or PyArray_MapIterNextRun, which does the jump and the step. WDYT?

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