Skip to content

topk

topk(
    scores: array,
    ratio: Optional[Union[float, int]],
    batch_indices: array,
    min_score: Optional[float] = None,
    tol: float = 1e-07,
) -> array

Selects the nodes with the highest scores in each graph.

If min_score is None, keeps the \(k\) best nodes of each graph, with \(k = \lceil \mathrm{ratio} \cdot N \rceil\) for a ratio smaller than 1 and \(k = \mathrm{ratio}\) otherwise (all the nodes of graphs with fewer than \(k\) nodes). Otherwise, keeps the nodes whose score is larger than min_score, and the best node of each graph in all cases.

Parameters:

Name Type Description Default
scores array

Score of each node, of shape [num_nodes].

required
ratio Optional[Union[float, int]]

The pooling ratio, or the number of nodes to keep per graph. Ignored if min_score is given.

required
batch_indices array

Graph of each node, of shape [num_nodes].

required
min_score Optional[float]

Minimal score of the kept nodes. Default: None

None
tol float

Tolerance on the best score of each graph, used with min_score. Default: 1e-7

1e-07

Returns:

Type Description
array

The indices of the kept nodes. Without min_score, they are grouped

array

by graph, by decreasing score; with min_score, in increasing order.

Example:

import mlx.core as mx
from mlx_graphs.nn import topk

scores = mx.array([0.1, 0.9, 0.5, 0.3, 0.7])
batch_indices = mx.array([0, 0, 0, 1, 1])
>>> topk(scores, 0.5, batch_indices)
array([1, 2, 4], dtype=int32)
Source code in mlx_graphs/nn/pooling/select.py
def topk(
    scores: mx.array,
    ratio: Optional[Union[float, int]],
    batch_indices: mx.array,
    min_score: Optional[float] = None,
    tol: float = 1e-7,
) -> mx.array:
    r"""Selects the nodes with the highest scores in each graph.

    If ``min_score`` is ``None``, keeps the :math:`k` best nodes of each graph,
    with :math:`k = \lceil \mathrm{ratio} \cdot N \rceil` for a ratio smaller
    than 1 and :math:`k = \mathrm{ratio}` otherwise (all the nodes of graphs
    with fewer than :math:`k` nodes). Otherwise, keeps the nodes whose score is
    larger than ``min_score``, and the best node of each graph in all cases.

    Args:
        scores: Score of each node, of shape ``[num_nodes]``.
        ratio: The pooling ratio, or the number of nodes to keep per graph.
            Ignored if ``min_score`` is given.
        batch_indices: Graph of each node, of shape ``[num_nodes]``.
        min_score: Minimal score of the kept nodes. Default: ``None``
        tol: Tolerance on the best score of each graph, used with
            ``min_score``. Default: ``1e-7``

    Returns:
        The indices of the kept nodes. Without ``min_score``, they are grouped
        by graph, by decreasing score; with ``min_score``, in increasing order.

    Example:

    .. code-block:: python

        import mlx.core as mx
        from mlx_graphs.nn import topk

        scores = mx.array([0.1, 0.9, 0.5, 0.3, 0.7])
        batch_indices = mx.array([0, 0, 0, 1, 1])
        >>> topk(scores, 0.5, batch_indices)
        array([1, 2, 4], dtype=int32)
    """
    if scores.size == 0:
        # before reading the scores back: MLX can crash when converting an
        # empty matmul output to numpy
        return mx.zeros((0,), dtype=mx.int32)
    score = _to_numpy(scores.reshape(-1)).astype(np.float64)
    batch = _to_numpy(batch_indices).reshape(-1).astype(np.int64)
    num_graphs = int(batch.max()) + 1

    if min_score is not None:
        scores_max = np.full(num_graphs, -np.inf)
        np.maximum.at(scores_max, batch, score)
        scores_min = np.minimum(scores_max[batch] - tol, min_score)
        return mx.array(np.nonzero(score > scores_min)[0].astype(np.int32))

    if ratio is None:
        raise ValueError(
            "At least one of the 'ratio' and 'min_score' parameters must be "
            "specified"
        )
    num_nodes = np.bincount(batch, minlength=num_graphs)
    if ratio >= 1:
        k = np.full(num_graphs, int(ratio))
    else:
        k = np.ceil(np.float32(ratio) * num_nodes.astype(np.float32)).astype(np.int64)

    # Sorted by graph, then by decreasing score.
    order = np.lexsort((-score, batch))
    starts = np.cumsum(num_nodes) - num_nodes
    rank = np.arange(order.size) - starts[batch[order]]
    return mx.array(order[rank < k[batch[order]]].astype(np.int32))

from mlx_graphs.nn import topk · mlx_graphs/nn/pooling/select.py