Skip to content

fps

fps(
    x: array,
    batch: Optional[array] = None,
    ratio: float = 0.5,
    random_start: bool = True,
    batch_size: Optional[int] = None,
) -> array

Farthest point sampling, from the "PointNet++: Deep Hierarchical Feature Learning on Point Sets in a Metric Space" paper.

Iteratively samples the point that is the most distant from the points already sampled. Each graph (point cloud) of the batch keeps \(\lceil \text{ratio} \cdot N_b \rceil\) of its \(N_b\) points.

On the GPU, every graph is sampled by one threadgroup of a Metal kernel; otherwise the graphs are sampled together with array operations.

Parameters:

Name Type Description Default
x array

Point coordinates (or features), of shape [N, num_features].

required
batch Optional[array]

Graph of each point, of shape [N], sorted in increasing order (as in a GraphDataBatch). Default: None (a single graph).

None
ratio float

Sampling ratio, in \((0, 1]\). Default: 0.5

0.5
random_start bool

If False, the first point of each graph is the starting point, as in PyG. Otherwise, a random point (from mx.random). Default: True

True
batch_size Optional[int]

The number of graphs. Default: None (inferred from batch).

None

Returns:

Type Description
array

The indices of the sampled points, of shape [num_samples], grouped

array

by graph and in sampling order.

Example:

import mlx.core as mx
from mlx_graphs.utils import fps

x = mx.array([[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0]])
batch = mx.array([0, 0, 0, 0])
index = fps(x, batch, ratio=0.5, random_start=False)
>>> index
array([0, 3], dtype=int32)
Source code in mlx_graphs/utils/clustering.py
def fps(
    x: mx.array,
    batch: Optional[mx.array] = None,
    ratio: float = 0.5,
    random_start: bool = True,
    batch_size: Optional[int] = None,
) -> mx.array:
    r"""Farthest point sampling, from the `"PointNet++: Deep Hierarchical
    Feature Learning on Point Sets in a Metric Space"
    <https://arxiv.org/abs/1706.02413>`_ paper.

    Iteratively samples the point that is the most distant from the points
    already sampled. Each graph (point cloud) of the batch keeps
    :math:`\lceil \text{ratio} \cdot N_b \rceil` of its :math:`N_b` points.

    On the GPU, every graph is sampled by one threadgroup of a Metal kernel;
    otherwise the graphs are sampled together with array operations.

    Args:
        x: Point coordinates (or features), of shape ``[N, num_features]``.
        batch: Graph of each point, of shape ``[N]``, sorted in increasing
            order (as in a ``GraphDataBatch``). Default: ``None`` (a single
            graph).
        ratio: Sampling ratio, in :math:`(0, 1]`. Default: ``0.5``
        random_start: If ``False``, the first point of each graph is the
            starting point, as in PyG. Otherwise, a random point (from
            ``mx.random``). Default: ``True``
        batch_size: The number of graphs. Default: ``None`` (inferred from
            ``batch``).

    Returns:
        The indices of the sampled points, of shape ``[num_samples]``, grouped
        by graph and in sampling order.

    Example:

    .. code-block:: python

        import mlx.core as mx
        from mlx_graphs.utils import fps

        x = mx.array([[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0]])
        batch = mx.array([0, 0, 0, 0])
        index = fps(x, batch, ratio=0.5, random_start=False)
        >>> index
        array([0, 3], dtype=int32)
    """
    if not 0.0 < ratio <= 1.0:
        raise ValueError(f"ratio must be in (0, 1], got {ratio}")
    x = x.reshape(x.shape[0], -1) if x.ndim != 2 else x
    num_points = x.shape[0]
    batch_np = _batch_vector(batch, num_points, "batch")
    if batch_np.size > 1 and np.any(np.diff(batch_np) < 0):
        raise ValueError("fps expects `batch` to be sorted in increasing order")
    if batch_size is None:
        batch_size = int(batch_np.max(initial=-1)) + 1 if batch is not None else 1
    sizes = np.bincount(batch_np, minlength=batch_size)[:batch_size]
    ptr = np.zeros(batch_size + 1, dtype=np.int64)
    np.cumsum(sizes, out=ptr[1:])
    # same float32 arithmetic as PyG for the number of samples
    counts = np.ceil(sizes.astype(np.float32) * np.float32(ratio)).astype(np.int64)
    out_ptr = np.zeros(batch_size + 1, dtype=np.int64)
    np.cumsum(counts, out=out_ptr[1:])
    if out_ptr[-1] == 0:
        return mx.zeros((0,), dtype=mx.int32)

    if random_start:
        start = np.floor(np.array(mx.random.uniform(shape=(batch_size,))) * sizes)
        start = np.minimum(start.astype(np.int64), np.maximum(sizes - 1, 0))
    else:
        start = np.zeros(batch_size, dtype=np.int64)

    pos = x if mx.issubdtype(x.dtype, mx.floating) else x.astype(mx.float32)
    if _use_metal() and num_points < 2**31:
        pos = pos.astype(mx.float32)
        threads = min(_FPS_MAX_THREADS, max(32, 1 << int(sizes.max() - 1).bit_length()))
        out, _ = _fps_kernel()(
            inputs=[
                mx.stop_gradient(pos),
                mx.array(ptr.astype(np.int32)),
                mx.array(out_ptr.astype(np.int32)),
                mx.array(start.astype(np.int32)),
            ],
            template=[("DIM", pos.shape[1])],
            grid=(threads * batch_size, 1, 1),
            threadgroup=(threads, 1, 1),
            output_shapes=[(int(out_ptr[-1]),), (num_points,)],
            output_dtypes=[mx.int32, mx.float32],
        )
        return out
    return _fps_reference(mx.stop_gradient(pos), ptr, counts, start)

from mlx_graphs.utils import fps · mlx_graphs/utils/clustering.py