Skip to content

ENH: ufunc.at: call the inner loop once per subarray - #1

Closed
cakedev0 wants to merge 2 commits into
mainfrom
ufunc-at-rows
Closed

cakedev0 wants to merge 2 commits into
mainfrom
ufunc-at-rows

Conversation

@cakedev0

@cakedev0 cakedev0 commented Nov 12, 2026 •

Copy link
Copy Markdown
Owner

PR summary

np.add.at(sums, labels, rows) with a 2-D sums is ~30x slower than it needs to be. This is the scatter-add of mini-batch k-means (sum the rows of each cluster), and FAISS replaced it with a SciPy sparse product for that reason (facebookresearch/faiss#5849).

When the indices select subarrays, ufunc.at cannot use the indexed loops of numpy#23136 (they need a 1-D target), so it falls back to the loop of numpy#22889, which calls the inner loop once per element with count = 1. A profile of the case below shows ~20% of the time in FLOAT_pairwise_sum: with zero strides and out == in1, each one-element add takes the reduction branch of the add loop.

This PR calls the inner loop once per run of the last dimension instead, with the real strides. It only changes the no-cast, aligned path. numpy#23176 lists this case ("2d and more contiguous arrays could be sped up").

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.

The first commit fixes a bug this change exposed. np.negative(a[::4], out=out[::2]) on float32 reads a[:4]: when the output is not contiguous, an input stride equal to the itemsize in elements (4 for 4-byte types, 8 for 8-byte types) is taken for a contiguous input. It is in 2.5.4 too. np.negative.at on rows hits it once the inner loop gets the real strides.

Tests:

  • the new test_ufunc_at_subarrays compares against applying the ufunc one index at a time (rows and columns, strided, reversed and transposed targets, broadcast and non-contiguous values)
  • I 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
  • The new np.negative test fails on main.

First time contributor introduction

Not my first PR here (numpy#29837 and numpy#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 what the benchmarks show. It pointed at numpy.add.at and I remembered I had already wrote a numba-version of it for 2d arrays a couple of years ago because it was slow. I asked Claude to investigate and it came up with this, which looks like a very useful speedup.

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 trust Claude to write better code than me (sadly), and most importantly, I trust the tests and the benchmarks (those I can understand).

"I" in the PR summary part means Claude.

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>
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