diff --git a/benchmarks/benchmarks/bench_ufunc.py b/benchmarks/benchmarks/bench_ufunc.py index 90a837e4efda..85d00b3bcb29 100644 --- a/benchmarks/benchmarks/bench_ufunc.py +++ b/benchmarks/benchmarks/bench_ufunc.py @@ -94,10 +94,17 @@ def setup(self): self.vals = rng.random(10_000_000, dtype=np.float64) self.idx = rng.integers(1000, size=10_000_000).astype(np.intp) self.res = np.zeros(1000, dtype=self.vals.dtype) + # rows summed per label, as in mini-batch k-means + self.rows = rng.random((16384, 200), dtype=np.float32) + self.labels = rng.integers(256, size=16384).astype(np.intp) + self.row_sums = np.zeros((256, 200), dtype=np.float32) def time_sum_at(self): np.add.at(self.res, self.idx, self.vals) + def time_sum_at_rows(self): + np.add.at(self.row_sums, self.labels, self.rows) + def time_maximum_at(self): np.maximum.at(self.res, self.idx, self.vals) diff --git a/numpy/_core/src/umath/loops_unary.dispatch.c.src b/numpy/_core/src/umath/loops_unary.dispatch.c.src index 951aa5be5240..f335a6e2ac09 100644 --- a/numpy/_core/src/umath/loops_unary.dispatch.c.src +++ b/numpy/_core/src/umath/loops_unary.dispatch.c.src @@ -295,7 +295,7 @@ NPY_NO_EXPORT void NPY_CPU_DISPATCH_CURFX(@TYPE@_@kind@) { const npy_intp istride = istep / sizeof(STYPE); const npy_intp ostride = ostep / sizeof(STYPE); - if (istride == sizeof(STYPE) && ostride != 1) { + if (istride == 1 && ostride != 1) { // contiguous input, non-contiguous output TO_SIMD_SFX(simd_unary_cn_@intrin@)( (STYPE*)ip, (STYPE*)op, ostride, len diff --git a/numpy/_core/src/umath/ufunc_object.c b/numpy/_core/src/umath/ufunc_object.c index 834f1238d4cb..50d0f778b78c 100644 --- a/numpy/_core/src/umath/ufunc_object.c +++ b/numpy/_core/src/umath/ufunc_object.c @@ -6456,6 +6456,94 @@ ufunc_at__fast_iter(PyUFuncObject *ufunc, NPY_ARRAYMETHOD_FLAGS flags, return res; } +/* + * Like ufunc_at__fast_iter, but for indices that select subarrays (e.g. rows + * of a 2-D op1): call the inner loop once per run of the last dimension + * instead of once per element. + */ +static int +ufunc_at__subspace_iter(PyArrayMethodObject *ufuncimpl, + NPY_ARRAYMETHOD_FLAGS flags, + PyArrayMapIterObject *iter, PyArrayIterObject *iter2, + PyArrayMethod_Context *context) +{ + int buffersize; + int errormask = 0; + int res = 0; + PyArrayMethod_StridedLoop *strided_loop = NULL; + NpyAuxData *auxdata = NULL; + NPY_ARRAYMETHOD_FLAGS loop_flags; + NPY_BEGIN_THREADS_DEF; + + if (_get_bufsize_errmask(&buffersize, &errormask) < 0) { + return -1; + } + int nd = iter->nd; + /* + * The subspace is iterated in C order, so its inner loop covers whole + * multiples of the last dimension, along which op2 has a fixed stride. + */ + npy_intp run = iter->dimensions[nd - 1]; + npy_intp op1_stride = iter->subspace_strides[0]; + npy_intp strides[3]; + strides[0] = op1_stride; + if (iter2 != NULL) { + strides[1] = iter2->strides[nd - 1]; + strides[2] = op1_stride; + } + else { + strides[1] = op1_stride; + strides[2] = 0; + } + if (ufuncimpl->get_strided_loop(context, 1, 0, strides, + &strided_loop, &auxdata, &loop_flags) < 0) { + return -1; + } + flags = PyArrayMethod_COMBINED_FLAGS(flags, loop_flags); + + int needs_api = (flags & NPY_METH_REQUIRES_PYAPI) != 0; + if (!(flags & NPY_METH_NO_FLOATINGPOINT_ERRORS)) { + npy_clear_floatstatus_barrier((char*)&iter); + } + if (!needs_api) { + NPY_BEGIN_THREADS; + } + + for (npy_intp pos = 0; pos < iter->size; pos += run) { + char *dataptr[3]; + npy_intp count = run; + + dataptr[0] = iter->dataptr; + if (iter2 != NULL) { + PyArray_ITER_GOTO1D(iter2, pos); + dataptr[1] = PyArray_ITER_DATA(iter2); + dataptr[2] = iter->dataptr; + } + else { + dataptr[1] = iter->dataptr; + dataptr[2] = NULL; + } + + res = strided_loop(context, dataptr, &count, strides, auxdata); + if (res != 0) { + break; + } + + /* skip to the last element of the run, then step past it */ + iter->iter_count -= run - 1; + iter->subspace_ptrs[0] += (run - 1) * op1_stride; + PyArray_MapIterNext(iter); + } + + NPY_END_THREADS; + NPY_AUXDATA_FREE(auxdata); + + if (res == 0 && !(flags & NPY_METH_NO_FLOATINGPOINT_ERRORS)) { + res = _check_ufunc_fperr(errormask, "at"); + } + return res; +} + static int ufunc_at__slow_iter(PyUFuncObject *ufunc, NPY_ARRAYMETHOD_FLAGS flags, PyArrayMapIterObject *iter, PyArrayIterObject *iter2, @@ -6896,6 +6984,11 @@ ufunc_at(PyUFuncObject *ufunc, PyObject *args) op2_array, &context); } + else if ((iter->subspace_iter != NULL) && (iter->nd > 0) && + (iter->dimensions[iter->nd - 1] > 1)) { + res = ufunc_at__subspace_iter(ufuncimpl, flags, iter, iter2, + &context); + } else { /* Couldn't use the fastest path, use the faster path */ res = ufunc_at__fast_iter(ufunc, flags, iter, iter2, op1_array, diff --git a/numpy/_core/tests/test_ufunc.py b/numpy/_core/tests/test_ufunc.py index 8ad56e8cab78..e86268651b29 100644 --- a/numpy/_core/tests/test_ufunc.py +++ b/numpy/_core/tests/test_ufunc.py @@ -2413,6 +2413,52 @@ def test_ufunc_at_multiD(self): [121, 222, 323], [124, 225, 326]]]) + @pytest.mark.parametrize("dtype", [np.int32, np.float32, np.float64, + np.complex128]) + @pytest.mark.parametrize("ufunc", [np.add, np.maximum, np.negative]) + @pytest.mark.parametrize("axis", [0, 1]) + @pytest.mark.parametrize("view", ["contiguous", "strided", "reversed", + "transposed"]) + def test_ufunc_at_subarrays(self, dtype, ufunc, axis, view): + # one index array selecting whole rows (or columns) of a 2-D array, + # compared with applying the ufunc one index at a time + rng = np.random.default_rng(0) + views = { + "contiguous": lambda x: x[:, :-1].copy(), + "strided": lambda x: x[:, :-1], + "reversed": lambda x: x[::-1, ::-3], + "transposed": lambda x: x.T[::2], + } + base = rng.integers(-50, 50, (6, 10)).astype(dtype) + shape = views[view](base).shape + idx = np.array([3, 0, 3, -1, 2, 3]) + n = shape[1 - axis] + full = rng.integers(-50, 50, (len(idx), n)).astype(dtype) + if axis == 1: + full = full.T + if ufunc is np.negative: + values = [None] + else: + values = [full, full[..., ::-1].copy()[..., ::-1], dtype(7), + full[0] if axis == 0 else full[:, :1]] + for b in values: + a = views[view](base.copy()) + expected = a.copy() + for i, j in enumerate(idx): + sel = (j,) if axis == 0 else (slice(None), j) + if b is None: + expected[sel] = ufunc(expected[sel]) + else: + bi = np.broadcast_to(b, full.shape) + expected[sel] = ufunc(expected[sel], + bi[i] if axis == 0 else bi[:, i]) + index = idx if axis == 0 else (slice(None), idx) + if b is None: + ufunc.at(a, index) + else: + ufunc.at(a, index, b) + assert_array_equal(a, expected) + def test_ufunc_at_0D(self): a = np.array(0) np.add.at(a, (), 1) diff --git a/numpy/_core/tests/test_umath.py b/numpy/_core/tests/test_umath.py index 4559ff02bc62..8ed6508baf03 100644 --- a/numpy/_core/tests/test_umath.py +++ b/numpy/_core/tests/test_umath.py @@ -5535,3 +5535,15 @@ def test_hypot_error_message_single_arg(self): def test_hypot_error_message_multiple_args(self): with pytest.raises(TypeError, match="hypot\\(\\) takes .* but 4 were given"): np.hypot(1, 2, 3, 4) + + +@pytest.mark.parametrize("dtype", [np.int8, np.int16, np.int32, np.int64, + np.float32, np.float64]) +@pytest.mark.parametrize("istride", [1, 2, 4, 8]) +def test_negative_strided_input_and_output(dtype, istride): + # an input stride equal to the itemsize (in elements) was read as contiguous + a = np.arange(16 * istride, dtype=dtype) + out = np.zeros(32, dtype=dtype) + np.negative(a[::istride], out=out[::2]) + assert_array_equal(out[::2], -a[::istride]) + assert_array_equal(out[1::2], 0)