Skip to content

scatter_mul

scatter_mul(values: array, index: array, out_size: int) -> array

Computes the product of the values grouped by index (along axis 0).

Groups without any value are set to 1, as in PyG. MLX has no gradient for multiplicative scatters, so this function provides its own: the gradient of a value is the product of the other values of its group, which is also correct for groups containing zeros.

Parameters:

Name Type Description Default
values array

Input array of shape [num_values, ...].

required
index array

Array of shape [num_values] with the group of each value.

required
out_size int

Number of groups.

required

Returns:

Type Description
array

An array of shape [out_size, ...] with the product of each group.

Source code in mlx_graphs/utils/scatter.py
def scatter_mul(values: mx.array, index: mx.array, out_size: int) -> mx.array:
    """Computes the product of the values grouped by index (along axis 0).

    Groups without any value are set to 1, as in PyG. MLX has no gradient for
    multiplicative scatters, so this function provides its own: the gradient
    of a value is the product of the other values of its group, which is also
    correct for groups containing zeros.

    Args:
        values: Input array of shape ``[num_values, ...]``.
        index: Array of shape ``[num_values]`` with the group of each value.
        out_size: Number of groups.

    Returns:
        An array of shape ``[out_size, ...]`` with the product of each group.
    """
    out_shape = (out_size, *values.shape[1:])

    def _prod(x: mx.array) -> mx.array:
        return mx.ones(out_shape, dtype=x.dtype).at[index].multiply(x)

    @mx.custom_function
    def _scatter_mul(x: mx.array) -> mx.array:
        return _prod(x)

    @_scatter_mul.vjp
    def _scatter_mul_vjp(primals, cotangent, output):
        # a single primal is passed as is, several as a tuple
        x = primals if isinstance(primals, mx.array) else primals[0]
        is_zero = x == 0
        ones = mx.ones_like(x)
        zeros = mx.zeros_like(x)
        # product of the non-zero values and number of zeros of each group
        prod_nonzero = _prod(mx.where(is_zero, ones, x))[index]
        num_zeros = (
            mx.zeros(out_shape, dtype=mx.int32).at[index].add(is_zero.astype(mx.int32))
        )[index]
        # d(prod)/dx_i = prod_{j != i} x_j
        grad = mx.where(
            is_zero,
            mx.where(num_zeros == 1, prod_nonzero, zeros),
            mx.where(num_zeros == 0, prod_nonzero / mx.where(is_zero, ones, x), zeros),
        )
        return (cotangent[index] * grad,)

    return _scatter_mul(values)

from mlx_graphs.utils.scatter import scatter_mul · mlx_graphs/utils/scatter.py