Repository navigation
Conversation
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>
|
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>
|
The fix is now in #33327. I left the fix in this PR too for now because the new |
|
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. |
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
|
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). |
|
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. |
|
I'd say let's converge on this one first and then do a follow-up. |
|
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>
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). |
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.
|
The speedup is real and it is a valid use case (although not the most important one I would say). The new @cakedev0 Could you investigate that approach? |
|
Thank you! Indeed what you propose seems to be less code, I'm looking into it.
Personally, each time I used
|
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>
| 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); |
There was a problem hiding this comment.
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?
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-Dsumsis ~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.atwas 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.atis slow.PR summary
Context: every ufunc has a C "inner loop" with the signature
loop(pointers, count, strides). It processescountelements, moving each pointer by its stride after every element. Calling it has a fixed cost, which is negligible whencountis large and dominant whencountis 1.ufunc.athas a special path that avoids calling the loop withcount=1in the 1-D case, by doinga[idx[i]] += b[i]directly. In all other cases, it calls the loop once per element, withcount=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), wherelabelspicks whole rows ofsums), 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), withcount=last_dim_sizeand 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.atexists) only occur between different runs, and those are still processed one after the other.And this makes
numpy.add.atas fast as it should be in those cases (~30x faster on my machine)Detailed benchmarks
Median times on one P-core of a Core Ultra X7 358H:
Contiguous or strided
sumsand float32 or float64 give the same speed-up. One epoch of FAISS 1.16NumpyEmeanson 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:
test_ufunc_at_rows_and_columnscompares against applying the ufunc one index at a time (rows and columns, strided, reversed and transposed targets, broadcast and non-contiguous values)ufunc.atcalls (1 to 3 dims, two index arrays, views, 5 ufuncs and 5 dtypes) between main and this branch, with no differenceFirst 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.atand 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).