Skip to content

DenseLayout

DenseLayout(
    index: Optional[array],
    num_elements: int,
    dim_size: Optional[int] = None,
    max_num_elements: Optional[int] = None,
)

Host-side layout of a set of elements grouped by index into a dense [num_sets, max_set_size, ...] array, as PyG's to_dense_batch.

Elements keep their input order within their set and index does not need to be sorted. Unlike to_dense_batch(), the layout can be reused to go back from the dense array to the elements (from_dense()), with gathers only, so both directions are differentiable.

Parameters:

Name Type Description Default
index Optional[array]

Set of each element, of shape [num_elements]. None means a single set.

required
num_elements int

Number of elements (needed when index is None).

required
dim_size Optional[int]

Number of sets. Default: index.max() + 1

None
max_num_elements Optional[int]

Maximum number of elements per set. Elements beyond it are dropped. Default: the size of the largest set.

None

Methods:

Name Description
from_sizes

Builds the layout on the device, without reading index on the

to_dense

Converts x of shape [num_elements, ...] to a dense array of

from_dense

Gathers the rows of the (kept) elements of a dense array of shape

Source code in mlx_graphs/nn/aggr/utils.py
def __init__(
    self,
    index: Optional[mx.array],
    num_elements: int,
    dim_size: Optional[int] = None,
    max_num_elements: Optional[int] = None,
):
    if index is None:
        batch = np.zeros(num_elements, dtype=np.int64)
    else:
        batch = _to_numpy(index).reshape(-1).astype(np.int64)
    if dim_size is None:
        dim_size = int(batch.max()) + 1 if batch.size > 0 else 1
    counts = np.bincount(batch, minlength=dim_size)[:dim_size]
    order = np.argsort(batch, kind="stable")
    starts = np.cumsum(counts) - counts
    local = np.empty(batch.size, dtype=np.int64)
    valid = batch[order] < dim_size
    local[order[valid]] = np.arange(int(valid.sum())) - starts[batch[order[valid]]]
    local[order[~valid]] = np.iinfo(np.int64).max  # dropped
    if max_num_elements is None:
        size = int(counts.max(initial=0))
    else:
        size = int(max_num_elements)

    keep = np.nonzero(local < size)[0]
    flat = batch[keep] * size + local[keep]
    slots = np.full(dim_size * size, batch.size, dtype=np.int64)
    slots[flat] = keep
    mask = np.zeros(dim_size * size, dtype=bool)
    mask[flat] = True

    self.num_sets = dim_size
    self.size = size
    self.num_elements = batch.size
    self.all_kept = keep.size == batch.size
    self._slots = mx.array(slots.astype(np.int32))
    self._flat = mx.array(flat.astype(np.int32))
    self.mask = mx.array(mask.reshape(dim_size, size))

from_sizes classmethod

from_sizes(
    index: Optional[array],
    num_elements: int,
    num_sets: int,
    max_num_elements: int,
) -> DenseLayout

Builds the layout on the device, without reading index on the host: no GPU synchronization, and usable inside mx.compile().

The number of sets and the size of the largest set are not computed from index but given, e.g. the number of graphs of a batch and an upper bound of their number of nodes (max_num_elements is the padded size of the dense array, so a tight bound saves memory). Elements of sets larger than max_num_elements (beyond the first max_num_elements of their set), or with an index outside [0, num_sets), are dropped: to_dense() leaves them out and from_dense() returns zeros for them.

With max_num_elements equal to the size of the largest set, the layout is the one of DenseLayout(index, num_elements). A larger bound only adds padding, which masked attentions (e.g. GPSConv with attn_type="multihead") ignore; the linear attentions of SGFormer, Polynormer and the performer attention count the padding rows in their normalizers (as in PyG, where the padding is set by the largest graph of the batch), so their outputs then change slightly.

Parameters:

Name Type Description Default
index Optional[array]

Set of each element, of shape [num_elements]. None means a single set.

required
num_elements int

Number of elements.

required
num_sets int

Number of sets.

required
max_num_elements int

Size of the sets in the dense array.

required

Example:

batch_indices = mx.array([0, 0, 1, 1, 1])
layout = DenseLayout.from_sizes(
    batch_indices, 5, num_sets=2, max_num_elements=3
)
>>> layout.mask
array([[True, True, False],
       [True, True, True]], dtype=bool)
Source code in mlx_graphs/nn/aggr/utils.py
@classmethod
def from_sizes(
    cls,
    index: Optional[mx.array],
    num_elements: int,
    num_sets: int,
    max_num_elements: int,
) -> "DenseLayout":
    """Builds the layout on the device, without reading ``index`` on the
    host: no GPU synchronization, and usable inside :func:`mx.compile`.

    The number of sets and the size of the largest set are not computed
    from ``index`` but given, e.g. the number of graphs of a batch and an
    upper bound of their number of nodes (``max_num_elements`` is the
    padded size of the dense array, so a tight bound saves memory).
    Elements of sets larger than ``max_num_elements`` (beyond the first
    ``max_num_elements`` of their set), or with an ``index`` outside
    ``[0, num_sets)``, are dropped: :meth:`to_dense` leaves them out and
    :meth:`from_dense` returns zeros for them.

    With ``max_num_elements`` equal to the size of the largest set, the
    layout is the one of ``DenseLayout(index, num_elements)``. A larger
    bound only adds padding, which masked attentions (e.g.
    :class:`~mlx_graphs.nn.GPSConv` with ``attn_type="multihead"``)
    ignore; the linear attentions of :class:`~mlx_graphs.nn.SGFormer`,
    :class:`~mlx_graphs.nn.Polynormer` and the performer attention count
    the padding rows in their normalizers (as in PyG, where the padding is
    set by the largest graph of the batch), so their outputs then change
    slightly.

    Args:
        index: Set of each element, of shape ``[num_elements]``. ``None``
            means a single set.
        num_elements: Number of elements.
        num_sets: Number of sets.
        max_num_elements: Size of the sets in the dense array.

    Example:

    .. code-block:: python

        batch_indices = mx.array([0, 0, 1, 1, 1])
        layout = DenseLayout.from_sizes(
            batch_indices, 5, num_sets=2, max_num_elements=3
        )
        >>> layout.mask
        array([[True, True, False],
               [True, True, True]], dtype=bool)
    """
    n, size = int(num_elements), int(max_num_elements)
    num_sets = int(num_sets)
    if index is None:
        index = mx.zeros((n,), dtype=mx.int32)
    index = index.reshape(-1).astype(mx.int32)
    positions = mx.arange(n, dtype=mx.int32)
    # Rank of every element within its set (in input order): sort by
    # (set, position), then subtract the start of the set.
    valid = (index >= 0) & (index < num_sets)
    set_key = mx.where(valid, index, num_sets)  # invalid elements last
    key = set_key.astype(mx.int64) * max(n, 1) + positions.astype(mx.int64)
    order = mx.argsort(key).astype(mx.int32)
    counts = mx.zeros((num_sets + 1,), dtype=mx.int32).at[set_key].add(1)
    counts = counts[:num_sets]
    starts = mx.cumsum(counts) - counts
    sorted_set = mx.clip(index[order], 0, max(num_sets - 1, 0))
    local_sorted = positions - starts[sorted_set]
    local = mx.zeros((n,), dtype=mx.int32).at[order].add(local_sorted)

    keep = valid & (local < size)
    pad = num_sets * size  # one extra slot collecting the dropped elements
    flat = mx.where(keep, index * size + local, pad)
    slots = mx.zeros((pad + 1,), dtype=mx.int32).at[flat].add(positions - n) + n
    mask = mx.zeros((pad + 1,), dtype=mx.int32).at[flat].add(1)[:pad] > 0

    layout = cls.__new__(cls)
    layout.num_sets = num_sets
    layout.size = size
    layout.num_elements = n
    layout.all_kept = True  # dropped elements read the padding slot
    layout._slots = slots[:pad]
    layout._flat = flat
    layout._pad_slot = True
    layout.mask = mask.reshape(num_sets, size)
    return layout

to_dense

to_dense(x: array, fill_value: float = 0.0) -> array

Converts x of shape [num_elements, ...] to a dense array of shape [num_sets, size, ...] padded with fill_value.

Source code in mlx_graphs/nn/aggr/utils.py
def to_dense(self, x: mx.array, fill_value: float = 0.0) -> mx.array:
    """Converts ``x`` of shape ``[num_elements, ...]`` to a dense array of
    shape ``[num_sets, size, ...]`` padded with ``fill_value``."""
    pad = mx.full((1, *x.shape[1:]), fill_value, dtype=x.dtype)
    dense = mx.concatenate([x, pad], axis=0)[self._slots]
    return dense.reshape(self.num_sets, self.size, *x.shape[1:])

from_dense

from_dense(dense: array) -> array

Gathers the rows of the (kept) elements of a dense array of shape [num_sets, size, ...], in input order.

Source code in mlx_graphs/nn/aggr/utils.py
def from_dense(self, dense: mx.array) -> mx.array:
    """Gathers the rows of the (kept) elements of a dense array of shape
    ``[num_sets, size, ...]``, in input order."""
    if not self.all_kept:
        raise ValueError("Some elements were dropped by `max_num_elements`")
    flat = dense.reshape(self.num_sets * self.size, *dense.shape[2:])
    if getattr(self, "_pad_slot", False):
        # dropped elements of `from_sizes` read a zero row
        pad = mx.zeros((1, *flat.shape[1:]), dtype=flat.dtype)
        flat = mx.concatenate([flat, pad], axis=0)
    return flat[self._flat]

from mlx_graphs.nn.aggr import DenseLayout · mlx_graphs/nn/aggr/utils.py