`lax.pmean` with unequal `axis_index_groups` divides every group by the size of the first group
Description
Description
With axis_index_groups of different sizes, jax.lax.pmean divides each group's sum by the size of the
first group instead of the device's own group:
import os
os.environ["XLA_FLAGS"] = "--xla_force_host_platform_device_count=4"
import sys
import numpy as np
import jax
groups = [[0], [1, 2, 3]]
x = np.arange(4, dtype=np.float32) # device i holds the value i
f = jax.pmap(lambda v: jax.lax.pmean(v, "i", axis_index_groups=groups), axis_name="i")
got = np.asarray(f(x))
expected = np.array([0.0, 2.0, 2.0, 2.0], dtype=np.float32) # mean of {0}; mean of {1, 2, 3}
print("jax", jax.__version__, "got", got, "expected", expected)
sys.exit(0 if np.allclose(got, expected) else 1)Output: got [0. 6. 6. 6.] expected [0. 2. 2. 2.]. With groups = [[0, 1], [2]] and x = [1, 1, 1],
the mean of a constant comes out as [1, 1, 0.5].
The divisor comes from _axis_size, which computes psum(1, axis_name, axis_index_groups=...). For a
constant operand, _psum uses size = len(axis_index_groups[0]) for all devices
(jax/_src/lax/parallel.py, the "handle the constant case specially" branch). So psum of a constant is
also wrong:
jax.pmap(lambda v: jax.lax.psum(1, "i", axis_index_groups=[[0], [1, 2, 3]]), axis_name="i")(np.zeros(4))
# [1 1 1 1]; psum of jnp.ones_like(v) gives [1. 3. 3. 3.]The docstring allows unequal groups except on TPU ("Groups must cover all axis indices exactly once, and on TPUs all groups must be the same size"). If unequal groups are not meant to be supported, a check that raises would avoid the silent wrong result.
Expected
Each device receives the mean over its own group: [0, 2, 2, 2] above; psum(1, ...) gives each
device the size of its own group.
System info (python version, jaxlib version, accelerator, etc.)
JAX 0.11.2, jaxlib 0.11.2, CPU (4 host devices via --xla_force_host_platform_device_count),
Python 3.12, Linux x86_64.
Source: jax-ml/jax