Skip to content

scatter_softmax

scatter_softmax(
    values: array, index: array, out_size: int, axis: int = 0
) -> array

Computes the softmax of values that are scattered along a specified axis, grouped by index.

Parameters:

Name Type Description Default
values array

Input array containing values to be scattered. These values will undergo a scatter and softmax operation

required
index array

Array containing indices that determine the scatter of the 'values'.

required
out_size int

Size of the output array

required
axis int

Axis along which to scatter

0

Returns:

Type Description
array

The resulting array after applying scatter and softmax operations on the

array

input 'values'.

Example:

src = mx.array([1., 1., 1., 1.])
index = mx.array([0, 0, 1, 2])
num_nodes = src.shape[0]

scatter_softmax(src, index, num_nodes)
>>>  mx.array([0.5, 0.5, 1, 1])
Source code in mlx_graphs/utils/scatter.py
def scatter_softmax(
    values: mx.array, index: mx.array, out_size: int, axis: int = 0
) -> mx.array:
    """Computes the softmax of values that are scattered along a specified axis,
    grouped by index.

    Args:
        values: Input array containing values to be scattered. These values will
            undergo a scatter and softmax operation
        index: Array containing indices that determine the scatter of the 'values'.
        out_size: Size of the output array
        axis: Axis along which to scatter

    Returns:
        The resulting array after applying scatter and softmax operations on the
        input 'values'.

    Example:

    .. code-block:: python

        src = mx.array([1., 1., 1., 1.])
        index = mx.array([0, 0, 1, 2])
        num_nodes = src.shape[0]

        scatter_softmax(src, index, num_nodes)
        >>>  mx.array([0.5, 0.5, 1, 1])
    """
    out_shape = list(values.shape)
    out_shape[axis] = out_size

    # Subtracting the per-group maximum keeps exp() from overflowing. The
    # softmax does not depend on that shift, so no gradient needs to flow
    # through it, which skips the backward pass of the scatter-max.
    scatt_max = mx.full(out_shape, -float("inf"), dtype=values.dtype)
    scatt_max = mx.stop_gradient(scatt_max.at[index].maximum(values))
    out = mx.exp(values - scatt_max[index])

    scatt_sum = mx.zeros(out_shape, dtype=values.dtype).at[index].add(out)

    eps = 1e-16
    return out / (scatt_sum[index] + eps)

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