jax
jax copied to clipboard
jax.Array.sum silently ignores the `initial` argument
Description
Summary
jax.Array.sum accepts an initial argument in its signature but never forwards it to
jax.numpy.sum, so the initial value is silently discarded and the method returns a
numerically wrong result. No error or warning is raised. The sibling methods
Array.prod, Array.max and Array.min all forward initial correctly.
Reproducing the Bug
import jax.numpy as jnp
import numpy as np
x = jnp.array([1.0, 2.0, 3.0])
assert jnp.sum(x, initial=100) == 106.0
assert np.array([1.0, 2.0, 3.0]).sum(initial=100) == 106.0
assert x.sum(initial=100) == 106.0, x.sum(initial=100) # fails: 6.0
Also affected under jit and for integer dtypes:
import jax, jax.numpy as jnp
print(jax.jit(lambda x: x.sum(initial=100.0))(jnp.array([1., 2., 3.]))) # 6.0, want 106.0
print(jnp.array([1, 2, 3]).sum(initial=10)) # 6, want 16
Fix
Forward the argument. Verified: with this change x.sum(initial=100) returns 106.0,
jnp.array([]).sum(initial=1.0) returns 1.0, and all four properties above pass.
--- a/jax/_src/numpy/array_methods.py
+++ b/jax/_src/numpy/array_methods.py
@@ -435,5 +435,5 @@ def _sum(self: Array, axis: reductions.Axis = None, dtype: DTypeLike | None = No
Refer to :func:`jax.numpy.sum` for full documentation.
"""
return reductions.sum(self, axis=axis, dtype=dtype, out=out, keepdims=keepdims,
- where=where, promote_integers=promote_integers)
+ initial=initial, where=where,
+ promote_integers=promote_integers)
System info (python version, jaxlib version, accelerator, etc.)
JAX 0.11.2 / jaxlib 0.11.2 OS/architecture: Linux x86-64