Skip to content

API reference

Every public function and class of mlx_cluster. The Sparse matrix multiplication guide explains the conventions and performance of the SpMM functions.

Random walks and sampling

random_walk

random_walk(
    rowptr: mlx.core.array,
    col: mlx.core.array,
    start: mlx.core.array,
    rand: mlx.core.array,
    walk_length: int,
    *,
    stream: object | None = None,
) -> tuple

Uniform random walks.

Parameters:

Name Type Description Default
rowptr array

rowptr of graph in csr format.

required
col array

edges(col) in csr format.

required
start_indices array

starting nodes of graph from which sampling will be performed.

required
random_values array

random values (between 0 to 1)

required
walk_length (int)

walk length of random graph

required

Returns:

Type Description
tuple

tuple (mlx.core.array, mlx.core.array)

rejection_sampling

rejection_sampling(
    rowptr: mlx.core.array,
    col: mlx.core.array,
    start: mlx.core.array,
    walk_length: int,
    p: float,
    q: float,
    *,
    key: object | None = None,
    max_attempts: int = 1000,
    stream: object | None = None,
) -> tuple

node2vec biased random walks (rejection sampling).

Having moved t -> v, the next node x is a neighbor of v chosen with weight 1/p if x == t, 1 if x is a neighbor of t, and 1/q otherwise. A node without neighbors keeps the walk in place (edge id -1).

Random numbers are generated inside the kernel from a counter-based generator seeded by key, so the CPU and GPU produce identical walks for the same key.

Parameters:

Name Type Description Default
rowptr array

CSR row pointers (int64).

required
col array

CSR column indices (int64).

required
start array

Start nodes (int64).

required
walk_length int

Number of steps per walk.

required
p float

Return parameter; larger values make returning to the previous node less likely.

required
q float

In-out parameter; q > 1 keeps walks local (BFS-like), q < 1 pushes them outward (DFS-like).

required
key array

uint32 key with 2 elements, e.g. mx.random.key(0). If omitted, one is drawn from MLX's global RNG, so mx.random.seed makes walks reproducible.

None
max_attempts int

Rejection-sampling cap per step. After this many rejections the last candidate is accepted. Default 1000.

1000
stream Stream | Device

Where to run (mx.cpu or mx.gpu).

None

Returns:

Type Description
tuple (mlx.core.array, mlx.core.array

(nodes, edges) of

tuple

shapes [len(start), walk_length + 1] and

tuple

[len(start), walk_length], both int64.

neighbor_sample

neighbor_sample(
    colptr: mlx.core.array,
    row: mlx.core.array,
    input_node: mlx.core.array,
    num_neighbors: collections.abc.Sequence[int],
    replace: bool = False,
    directed: bool = True,
) -> tuple

Simple neighbor sampling without primitives.

Parameters:

Name Type Description Default
colptr array

Column pointers (CSC format)

required
row array

Row indices (CSC format)

required
input_node array

Input nodes to sample from

required
num_neighbors list[int]

List containing how many neighbors to sample in each hop

required
replace bool

Sample with replacement (Default to False)

False
directed bool

Directed graph (Default to True)

True

Returns:

Type Description
tuple (mlx.core.array, mlx.core.array, mlx.core.array, mlx.core.array

(samples, rows, cols, edges)

Heterogeneous graphs

hetero_neighbor_sample

hetero_neighbor_sample(
    colptr_dict: Mapping[EdgeType, array],
    row_dict: Mapping[EdgeType, array],
    seed_dict: Mapping[NodeType, array],
    num_neighbors: NumNeighbors,
    num_nodes_dict: Optional[Mapping[NodeType, int]] = None,
    replace: bool = False,
    directed: bool = True,
    seed: Optional[int] = None,
) -> HeteroSamplerOutput

Multi-hop neighbor sampling on a heterogeneous graph (GraphSAGE style).

For every edge type (src, rel, dst) and every hop, up to k incoming src neighbors are sampled for each dst node discovered at the previous hop (the seeds at hop 0).

Parameters:

Name Type Description Default
colptr_dict Mapping[EdgeType, array]

CSC column pointers per edge type. For (src, rel, dst) this has num_dst_nodes + 1 int64 entries.

required
row_dict Mapping[EdgeType, array]

CSC row indices (source node of each edge, sorted by destination) per edge type, int64.

required
seed_dict Mapping[NodeType, array]

Seed node ids per node type. Must not contain duplicates.

required
num_neighbors NumNeighbors

Fan-out per hop, e.g. [10, 5]. Either a single list used for every edge type, or a dict mapping each edge type to its own list. -1 takes all neighbors; 0 samples none. Shorter lists are padded with 0.

required
num_nodes_dict Optional[Mapping[NodeType, int]]

Optional number of nodes per node type (e.g. HeteroGraphData.num_nodes). Lets node types that only appear as a source use the faster dense id mapper.

None
replace bool

Sample with replacement.

False
directed bool

Only True is supported for heterogeneous graphs.

True
seed Optional[int]

Seed for the sampler's RNG. If None, one is drawn from MLX's global RNG, so mx.random.seed(...) makes sampling reproducible.

None

Returns:

Type Description
HeteroSamplerOutput

HeteroSamplerOutput

Example:

out = hetero_neighbor_sample(
    colptr_dict={("author", "writes", "paper"): colptr},
    row_dict={("author", "writes", "paper"): row},
    seed_dict={"paper": mx.array([0, 1], dtype=mx.int64)},
    num_neighbors=[10, 5],
)
out.node_id["author"]                         # sampled author ids
et = ("author", "writes", "paper")
edge_index = mx.stack([out.row[et], out.col[et]])
Source code in mlx_cluster/hetero.py
def hetero_neighbor_sample(
    colptr_dict: Mapping[EdgeType, mx.array],
    row_dict: Mapping[EdgeType, mx.array],
    seed_dict: Mapping[NodeType, mx.array],
    num_neighbors: NumNeighbors,
    num_nodes_dict: Optional[Mapping[NodeType, int]] = None,
    replace: bool = False,
    directed: bool = True,
    seed: Optional[int] = None,
) -> HeteroSamplerOutput:
    """Multi-hop neighbor sampling on a heterogeneous graph (GraphSAGE style).

    For every edge type ``(src, rel, dst)`` and every hop, up to ``k``
    incoming ``src`` neighbors are sampled for each ``dst`` node discovered
    at the previous hop (the seeds at hop 0).

    Args:
        colptr_dict: CSC column pointers per edge type. For ``(src, rel,
            dst)`` this has ``num_dst_nodes + 1`` int64 entries.
        row_dict: CSC row indices (source node of each edge, sorted by
            destination) per edge type, int64.
        seed_dict: Seed node ids per node type. Must not contain duplicates.
        num_neighbors: Fan-out per hop, e.g. ``[10, 5]``. Either a single
            list used for every edge type, or a dict mapping each edge type
            to its own list. ``-1`` takes all neighbors; ``0`` samples none.
            Shorter lists are padded with ``0``.
        num_nodes_dict: Optional number of nodes per node type (e.g.
            ``HeteroGraphData.num_nodes``). Lets node types that only appear
            as a source use the faster dense id mapper.
        replace: Sample with replacement.
        directed: Only ``True`` is supported for heterogeneous graphs.
        seed: Seed for the sampler's RNG. If ``None``, one is drawn from
            MLX's global RNG, so ``mx.random.seed(...)`` makes sampling
            reproducible.

    Returns:
        HeteroSamplerOutput

    Example:

    .. code-block:: python

        out = hetero_neighbor_sample(
            colptr_dict={("author", "writes", "paper"): colptr},
            row_dict={("author", "writes", "paper"): row},
            seed_dict={"paper": mx.array([0, 1], dtype=mx.int64)},
            num_neighbors=[10, 5],
        )
        out.node_id["author"]                         # sampled author ids
        et = ("author", "writes", "paper")
        edge_index = mx.stack([out.row[et], out.col[et]])
    """
    edge_types = list(colptr_dict.keys())
    if not edge_types:
        raise ValueError("colptr_dict must contain at least one edge type")
    if set(row_dict.keys()) != set(edge_types):
        raise ValueError("colptr_dict and row_dict must have the same edge types")
    if not seed_dict:
        raise ValueError("seed_dict must contain at least one node type")

    rel_types = [edge_type_to_str(et) for et in edge_types]

    # Node types: everything mentioned by edge types, seeds or num_nodes_dict,
    # in first-seen order (deterministic output ordering).
    node_types: List[str] = []
    for et in edge_types:
        for nt in (et[0], et[2]):
            if nt not in node_types:
                node_types.append(nt)
    for nt in list(seed_dict.keys()) + list((num_nodes_dict or {}).keys()):
        if nt not in node_types:
            node_types.append(nt)

    fanouts = _resolve_num_neighbors(num_neighbors, edge_types)

    seeds = {}
    for nt, s in seed_dict.items():
        s = s if isinstance(s, mx.array) else mx.array(s)
        seeds[nt] = s.astype(mx.int64).reshape(-1)

    if seed is None:
        seed = int(mx.random.randint(0, 2**31 - 1, shape=()).item())

    node_id, row, col, edge_id, n_nodes, n_edges = _hetero_neighbor_sample(
        node_types,
        edge_types,
        {rt: colptr_dict[et] for rt, et in zip(rel_types, edge_types)},
        {rt: row_dict[et] for rt, et in zip(rel_types, edge_types)},
        seeds,
        {rt: fanouts[et] for rt, et in zip(rel_types, edge_types)},
        {k: int(v) for k, v in (num_nodes_dict or {}).items()},
        bool(replace),
        bool(directed),
        int(seed),
    )

    to_et = dict(zip(rel_types, edge_types))
    return HeteroSamplerOutput(
        node_id={nt: node_id[nt] for nt in node_types},
        row={to_et[rt]: row[rt] for rt in rel_types},
        col={to_et[rt]: col[rt] for rt in rel_types},
        edge_id={to_et[rt]: edge_id[rt] for rt in rel_types},
        num_sampled_nodes={nt: list(n_nodes[nt]) for nt in node_types},
        num_sampled_edges={to_et[rt]: list(n_edges[rt]) for rt in rel_types},
    )

HeteroSamplerOutput

Bases: NamedTuple

Result of hetero_neighbor_sample().

Attributes:

Name Type Description
node_id Dict[NodeType, array]

Global ids of the sampled nodes per node type. For each seeded node type, the first len(seed_dict[t]) entries are the seeds in the order given.

row Dict[EdgeType, array]

Per edge type, local index (into node_id[src]) of each sampled edge's source node.

col Dict[EdgeType, array]

Per edge type, local index (into node_id[dst]) of each sampled edge's destination node. mx.stack([row, col]) is the sampled subgraph's edge_index for that edge type.

edge_id Dict[EdgeType, array]

Per edge type, offset of each sampled edge in row_dict[edge_type] (i.e. its position in CSC order).

num_sampled_nodes Dict[NodeType, List[int]]

Per node type, [#seeds, #new at hop 1, ...].

num_sampled_edges Dict[EdgeType, List[int]]

Per edge type, [#edges at hop 1, ...].

build_metapath_csr

build_metapath_csr(
    edge_index_dict: Mapping[EdgeType, array],
    metapath: Sequence[EdgeType],
    num_nodes_dict: Optional[Mapping[NodeType, int]] = None,
) -> MetaPathCSR

Builds the CSR adjacency used by metapath_random_walk().

This sorts every relation once, so compute it once per graph and reuse it.

Parameters:

Name Type Description Default
edge_index_dict Mapping[EdgeType, array]

(src, rel, dst) -> [2, num_edges] edge indices, with node ids local to each node type (as in HeteroGraphData).

required
metapath Sequence[EdgeType]

List of (src, rel, dst) edge types. Each edge type must end at the node type the next one starts from.

required
num_nodes_dict Optional[Mapping[NodeType, int]]

Optional number of nodes per node type. Missing types are inferred from the largest node id in edge_index_dict.

None

Returns:

Type Description
MetaPathCSR

MetaPathCSR

Source code in mlx_cluster/metapath.py
def build_metapath_csr(
    edge_index_dict: Mapping[EdgeType, mx.array],
    metapath: Sequence[EdgeType],
    num_nodes_dict: Optional[Mapping[NodeType, int]] = None,
) -> MetaPathCSR:
    """Builds the CSR adjacency used by :func:`metapath_random_walk`.

    This sorts every relation once, so compute it once per graph and reuse it.

    Args:
        edge_index_dict: ``(src, rel, dst) -> [2, num_edges]`` edge indices,
            with node ids local to each node type (as in ``HeteroGraphData``).
        metapath: List of ``(src, rel, dst)`` edge types. Each edge type must
            end at the node type the next one starts from.
        num_nodes_dict: Optional number of nodes per node type. Missing types
            are inferred from the largest node id in ``edge_index_dict``.

    Returns:
        MetaPathCSR
    """
    metapath = _validate_metapath(metapath)
    missing = [et for et in metapath if et not in edge_index_dict]
    if missing:
        raise ValueError(f"Edge types {missing} are not in edge_index_dict")

    num_nodes = _infer_num_nodes(edge_index_dict, num_nodes_dict)

    unique_rels: List[EdgeType] = []
    for et in metapath:
        if et not in unique_rels:
            unique_rels.append(et)

    rowptrs, cols, rp_off, col_off = [], [], [], []
    rp_cursor, col_cursor = 0, 0
    for et in unique_rels:
        src_type = et[0]
        n_src = num_nodes.get(src_type, 0)
        ei = np.asarray(edge_index_dict[et]).astype(np.int64)
        src, dst = ei[0], ei[1]
        order = np.argsort(src, kind="stable")
        counts = np.bincount(src, minlength=n_src)
        rowptr = np.concatenate([[0], np.cumsum(counts)]).astype(np.int64)
        rowptrs.append(rowptr)
        cols.append(dst[order])
        rp_off.append(rp_cursor)
        col_off.append(col_cursor)
        rp_cursor += rowptr.shape[0]
        col_cursor += dst.shape[0]

    return MetaPathCSR(
        metapath=metapath,
        rowptr=mx.array(np.concatenate(rowptrs)),
        col=mx.array(np.concatenate(cols)),
        rowptr_offset=mx.array(np.array(rp_off, dtype=np.int64)),
        col_offset=mx.array(np.array(col_off, dtype=np.int64)),
        rel_ids=[unique_rels.index(et) for et in metapath],
        num_nodes_dict=num_nodes,
    )

metapath_random_walk

metapath_random_walk(
    csr: MetaPathCSR,
    start: array,
    walk_length: int,
    rand: Optional[array] = None,
    stream: Optional[Stream] = None,
) -> Tuple[array, array]

Meta-path guided uniform random walks.

Step l of every walk follows edge type metapath[l % len(metapath)], choosing uniformly among the current node's neighbors of that type. If a node has no such neighbor, the walk stops and the remaining entries are -1.

Parameters:

Name Type Description Default
csr MetaPathCSR required
start array

Start node ids, local to metapath[0][0]'s node type.

required
walk_length int

Number of steps per walk. If it is longer than the meta-path, the meta-path must be cyclic (end where it starts).

required
rand Optional[array]

Optional uniform [0, 1) values of shape [len(start), walk_length]. Drawn from MLX's RNG if omitted, so mx.random.seed makes walks reproducible.

None
stream Optional[Stream]

Stream or device to run on (mx.cpu or mx.gpu).

None

Returns:

Type Description
tuple `(nodes, edges)`

nodes is [len(start), walk_length + 1]

array

local node ids (the type of column j is

Tuple[array, array]

metapath_node_types(metapath, walk_length)[j]); edges is

Tuple[array, array]

[len(start), walk_length] edge offsets within each relation's CSR.

Example:

metapath = [
    ("author", "writes", "paper"),
    ("paper", "published_in", "venue"),
    ("venue", "publishes", "paper"),
    ("paper", "written_by", "author"),
]
csr = build_metapath_csr(edge_index_dict, metapath)
nodes, _ = metapath_random_walk(csr, mx.arange(10), walk_length=8)
Source code in mlx_cluster/metapath.py
def metapath_random_walk(
    csr: MetaPathCSR,
    start: mx.array,
    walk_length: int,
    rand: Optional[mx.array] = None,
    stream: Optional[mx.Stream] = None,
) -> Tuple[mx.array, mx.array]:
    """Meta-path guided uniform random walks.

    Step ``l`` of every walk follows edge type ``metapath[l % len(metapath)]``,
    choosing uniformly among the current node's neighbors of that type. If a
    node has no such neighbor, the walk stops and the remaining entries are
    ``-1``.

    Args:
        csr: Output of :func:`build_metapath_csr`.
        start: Start node ids, local to ``metapath[0][0]``'s node type.
        walk_length: Number of steps per walk. If it is longer than the
            meta-path, the meta-path must be cyclic (end where it starts).
        rand: Optional uniform ``[0, 1)`` values of shape
            ``[len(start), walk_length]``. Drawn from MLX's RNG if omitted,
            so ``mx.random.seed`` makes walks reproducible.
        stream: Stream or device to run on (``mx.cpu`` or ``mx.gpu``).

    Returns:
        tuple ``(nodes, edges)``: ``nodes`` is ``[len(start), walk_length + 1]``
        local node ids (the type of column ``j`` is
        ``metapath_node_types(metapath, walk_length)[j]``); ``edges`` is
        ``[len(start), walk_length]`` edge offsets within each relation's CSR.

    Example:

    .. code-block:: python

        metapath = [
            ("author", "writes", "paper"),
            ("paper", "published_in", "venue"),
            ("venue", "publishes", "paper"),
            ("paper", "written_by", "author"),
        ]
        csr = build_metapath_csr(edge_index_dict, metapath)
        nodes, _ = metapath_random_walk(csr, mx.arange(10), walk_length=8)
    """
    metapath = csr.metapath
    m = len(metapath)
    if walk_length < 1:
        raise ValueError("walk_length must be >= 1")
    if walk_length > m and metapath[-1][2] != metapath[0][0]:
        raise ValueError(
            f"walk_length ({walk_length}) is longer than the metapath ({m}), "
            "so the metapath must be cyclic: it ends at "
            f"'{metapath[-1][2]}' but starts at '{metapath[0][0]}'"
        )

    start = mx.array(start) if not isinstance(start, mx.array) else start
    start = start.astype(mx.int64).reshape(-1)
    if rand is None:
        rand = mx.random.uniform(shape=(start.shape[0], walk_length))
    rand = rand.astype(mx.float32)

    step_rel = mx.array(
        np.array([csr.rel_ids[l % m] for l in range(walk_length)], dtype=np.int64)
    )
    return _metapath_random_walk(
        csr.rowptr,
        csr.col,
        csr.rowptr_offset,
        csr.col_offset,
        step_rel,
        start,
        rand,
        walk_length,
        stream=stream,
    )

metapath_node_types

metapath_node_types(
    metapath: Sequence[EdgeType], walk_length: int
) -> List[str]

Node type of each of the walk_length + 1 positions of a walk.

Source code in mlx_cluster/metapath.py
def metapath_node_types(metapath: Sequence[EdgeType], walk_length: int) -> List[str]:
    """Node type of each of the ``walk_length + 1`` positions of a walk."""
    m = len(metapath)
    return [metapath[0][0]] + [metapath[l % m][2] for l in range(walk_length)]

MetaPathCSR

Bases: NamedTuple

Per-relation CSR adjacency for the relations of a meta-path.

Attributes:

Name Type Description
metapath List[EdgeType]

The meta-path, a list of (src, rel, dst) edge types.

rowptr array

All relations' CSR row pointers, concatenated (int64).

col array

All relations' CSR column indices, concatenated (int64).

rowptr_offset array

Start of each relation inside rowptr (int64).

col_offset array

Start of each relation inside col (int64).

rel_ids List[int]

For each meta-path position, the relation id it uses.

num_nodes_dict Dict[NodeType, int]

Number of nodes per node type.

Sparse matrix multiplication

spmm_coo

spmm_coo(
    row: array,
    col: array,
    x: array,
    values: Optional[array] = None,
    num_rows: Optional[int] = None,
    reduce: SpMMReduce = "sum",
    *,
    stream=None,
) -> array

SpMM with A given as a COO edge list (any edge order).

out[r] = reduce_{e : row[e] == r} values[e] * x[col[e]]

GPU kernel: one thread per (edge, feature) with atomic adds (max/min use integer atomics on an order-preserving encoding of the floats).

Parameters:

Name Type Description Default
row array

[num_edges] destination node of each edge.

required
col array

[num_edges] source node of each edge.

required
x array

[num_nodes, features] node features.

required
values Optional[array]

optional [num_edges] edge weights.

None
num_rows Optional[int]

number of output rows. Defaults to x.shape[0].

None
reduce SpMMReduce

how the messages values[e] * x[col[e]] arriving at a row are combined, per feature: "sum" (or "add"), "mean", "max" or "min". Rows without edges give 0 for every reduction. For "max"/"min", the gradient goes to every edge whose message equals the output (ties included), as in MLX's scatter max/min; mx.jvp is not supported for them.

'sum'

Returns:

Type Description
array

[num_rows, features] array with the dtype of x.

Source code in mlx_cluster/sparse.py
def spmm_coo(
    row: mx.array,
    col: mx.array,
    x: mx.array,
    values: Optional[mx.array] = None,
    num_rows: Optional[int] = None,
    reduce: SpMMReduce = "sum",
    *,
    stream=None,
) -> mx.array:
    """SpMM with ``A`` given as a COO edge list (any edge order).

    ``out[r] = reduce_{e : row[e] == r} values[e] * x[col[e]]``

    GPU kernel: one thread per (edge, feature) with atomic adds (``max``/``min``
    use integer atomics on an order-preserving encoding of the floats).

    Args:
        row: ``[num_edges]`` destination node of each edge.
        col: ``[num_edges]`` source node of each edge.
        x: ``[num_nodes, features]`` node features.
        values: optional ``[num_edges]`` edge weights.
        num_rows: number of output rows. Defaults to ``x.shape[0]``.
        reduce: how the messages ``values[e] * x[col[e]]`` arriving at a row
            are combined, per feature: ``"sum"`` (or ``"add"``), ``"mean"``,
            ``"max"`` or ``"min"``. Rows without edges give ``0`` for every
            reduction. For ``"max"``/``"min"``, the gradient goes to every edge
            whose message equals the output (ties included), as in MLX's
            ``scatter`` max/min; ``mx.jvp`` is not supported for them.

    Returns:
        ``[num_rows, features]`` array with the dtype of ``x``.
    """
    reduce = _check_reduce(reduce)
    n = x.shape[0] if num_rows is None else num_rows
    out = _spmm_coo(row, col, x, n, values, reduce=_kernel_reduce(reduce), stream=stream)
    if reduce == "mean":
        deg = mx.zeros((n,), dtype=mx.int32).at[row].add(1).astype(mx.float32)
        out = out / mx.maximum(deg, 1.0)[:, None]
    return out.astype(x.dtype)

spmm_csr

spmm_csr(
    rowptr: array,
    col: array,
    x: array,
    values: Optional[array] = None,
    reduce: SpMMReduce = "sum",
    *,
    long_rows: Optional[LongRows] = None,
    transpose: Optional[CSRTranspose] = None,
    stream=None,
) -> array

SpMM with A given in CSR format (see coo_to_csr()).

GPU kernel: one thread per (row, feature), no atomics, deterministic.

Parameters:

Name Type Description Default
rowptr array

[num_rows + 1] row pointer.

required
col array

[num_edges] source node of each edge, in CSR order.

required
x array

[num_nodes, features] node features.

required
values Optional[array]

optional [num_edges] edge weights, in CSR order.

None
reduce SpMMReduce

how the messages values[e] * x[col[e]] arriving at a row are combined, per feature: "sum" (or "add"), "mean", "max" or "min". Rows without edges give 0 for every reduction. For "max"/"min", the gradient goes to every edge whose message equals the output (ties included), as in MLX's scatter max/min; mx.jvp is not supported for them.

'sum'
long_rows Optional[LongRows]

optional LongRows (CSR.long_rows from coo_to_csr()). Strongly recommended for graphs with hub nodes: without it a single thread loops over each hub's edges.

None
transpose Optional[CSRTranspose]

optional CSRTranspose (CSR.transpose). With it, the gradient w.r.t. x uses the CSR kernel on the transpose (deterministic); without it, the COO kernel.

None

Returns:

Type Description
array

[rowptr.size - 1, features] array with the dtype of x.

Source code in mlx_cluster/sparse.py
def spmm_csr(
    rowptr: mx.array,
    col: mx.array,
    x: mx.array,
    values: Optional[mx.array] = None,
    reduce: SpMMReduce = "sum",
    *,
    long_rows: Optional[LongRows] = None,
    transpose: Optional[CSRTranspose] = None,
    stream=None,
) -> mx.array:
    """SpMM with ``A`` given in CSR format (see :func:`coo_to_csr`).

    GPU kernel: one thread per (row, feature), no atomics, deterministic.

    Args:
        rowptr: ``[num_rows + 1]`` row pointer.
        col: ``[num_edges]`` source node of each edge, in CSR order.
        x: ``[num_nodes, features]`` node features.
        values: optional ``[num_edges]`` edge weights, in CSR order.
        reduce: how the messages ``values[e] * x[col[e]]`` arriving at a row
            are combined, per feature: ``"sum"`` (or ``"add"``), ``"mean"``,
            ``"max"`` or ``"min"``. Rows without edges give ``0`` for every
            reduction. For ``"max"``/``"min"``, the gradient goes to every edge
            whose message equals the output (ties included), as in MLX's
            ``scatter`` max/min; ``mx.jvp`` is not supported for them.
        long_rows: optional :class:`LongRows` (``CSR.long_rows`` from
            :func:`coo_to_csr`). Strongly recommended for graphs with hub
            nodes: without it a single thread loops over each hub's edges.
        transpose: optional :class:`CSRTranspose` (``CSR.transpose``). With
            it, the gradient w.r.t. ``x`` uses the CSR kernel on the
            transpose (deterministic); without it, the COO kernel.

    Returns:
        ``[rowptr.size - 1, features]`` array with the dtype of ``x``.
    """
    reduce = _check_reduce(reduce)
    kwargs = {}
    if long_rows is not None:
        kwargs.update(
            long_rows=long_rows.rows,
            chunk_ptr=long_rows.chunk_ptr,
            chunk_start=long_rows.chunk_start,
            chunk_end=long_rows.chunk_end,
            long_row_threshold=long_rows.threshold,
        )
    if transpose is not None:
        kwargs.update(t_rowptr=transpose.rowptr, t_col=transpose.col, t_perm=transpose.perm)
        lt = transpose.long_rows
        if lt is not None:
            kwargs.update(
                t_long_rows=lt.rows,
                t_chunk_ptr=lt.chunk_ptr,
                t_chunk_start=lt.chunk_start,
                t_chunk_end=lt.chunk_end,
                t_long_row_threshold=lt.threshold,
            )
    out = _spmm_csr(
        rowptr, col, x, values, reduce=_kernel_reduce(reduce), stream=stream, **kwargs
    )
    if reduce == "mean":
        deg = (rowptr[1:] - rowptr[:-1]).astype(mx.float32)
        out = out / mx.maximum(deg, 1.0)[:, None]
    return out.astype(x.dtype)

coo_to_csr

coo_to_csr(
    row: array,
    col: array,
    num_rows: int,
    values: Optional[array] = None,
    long_row_threshold: Optional[int] = 256,
    chunk_size: int = 2048,
    transpose: bool = True,
    num_cols: Optional[int] = None,
) -> CSR

Converts a COO edge list into CSR (sorted by row).

This needs a sort, so compute it once per graph and reuse it.

Parameters:

Name Type Description Default
long_row_threshold Optional[int]

rows with more edges than this get the load-balanced long-row path in spmm_csr() (see LongRows). None disables it and keeps the conversion fully lazy (no host read-back), e.g. inside mx.compile.

256
chunk_size int

maximum number of edges per long-row chunk.

2048
transpose bool

also build the transposed CSR (one more sort, ~3 extra index arrays) so the backward pass of spmm_csr() uses the CSR kernel: deterministic and atomic-free. Set False to save the memory when you only need the forward pass.

True
num_cols Optional[int]

number of columns (source nodes), i.e. x.shape[0] in spmm_csr(). Defaults to num_rows (square adjacency).

None
Source code in mlx_cluster/sparse.py
def coo_to_csr(
    row: mx.array,
    col: mx.array,
    num_rows: int,
    values: Optional[mx.array] = None,
    long_row_threshold: Optional[int] = 256,
    chunk_size: int = 2048,
    transpose: bool = True,
    num_cols: Optional[int] = None,
) -> CSR:
    """Converts a COO edge list into CSR (sorted by ``row``).

    This needs a sort, so compute it once per graph and reuse it.

    Args:
        long_row_threshold: rows with more edges than this get the
            load-balanced long-row path in :func:`spmm_csr` (see
            :class:`LongRows`). ``None`` disables it and keeps the conversion
            fully lazy (no host read-back), e.g. inside ``mx.compile``.
        chunk_size: maximum number of edges per long-row chunk.
        transpose: also build the transposed CSR (one more sort, ~3 extra
            index arrays) so the backward pass of :func:`spmm_csr` uses the
            CSR kernel: deterministic and atomic-free. Set ``False`` to save
            the memory when you only need the forward pass.
        num_cols: number of columns (source nodes), i.e. ``x.shape[0]`` in
            :func:`spmm_csr`. Defaults to ``num_rows`` (square adjacency).
    """
    row = row.astype(mx.int64)
    perm = mx.argsort(row)
    # int32 counts: MLX's GPU scatter does not support int64 inputs/updates.
    counts = mx.zeros((num_rows,), dtype=mx.int32).at[row].add(1)
    rowptr = mx.concatenate(
        [mx.zeros((1,), dtype=mx.int64), mx.cumsum(counts.astype(mx.int64))]
    )
    long_rows = (
        None
        if long_row_threshold is None
        else build_long_rows(rowptr, long_row_threshold, chunk_size)
    )
    col_csr = col.astype(mx.int64)[perm]

    csr_t = None
    if transpose:
        n_cols = num_rows if num_cols is None else num_cols
        perm_t = mx.argsort(col_csr)  # CSR edge index of each transposed edge
        counts_t = mx.zeros((n_cols,), dtype=mx.int32).at[col_csr].add(1)
        rowptr_t = mx.concatenate(
            [mx.zeros((1,), dtype=mx.int64), mx.cumsum(counts_t.astype(mx.int64))]
        )
        csr_t = CSRTranspose(
            rowptr=rowptr_t,
            col=row[perm][perm_t],
            perm=perm_t.astype(mx.int64),
            long_rows=(
                None
                if long_row_threshold is None
                else build_long_rows(rowptr_t, long_row_threshold, chunk_size)
            ),
            edge=perm[perm_t],
        )

    return CSR(
        rowptr=rowptr,
        col=col_csr,
        values=None if values is None else values[perm],
        perm=perm,
        long_rows=long_rows,
        transpose=csr_t,
    )

sddmm

sddmm(
    row: mlx.core.array,
    col: mlx.core.array,
    a: mlx.core.array,
    b: mlx.core.array,
    *,
    stream: object | None = None,
) -> mlx.core.array

Per-edge dot product: out[e] = <a[row[e]], b[col[e]]>.

Returns:

Type Description
array

float32 array of shape [num_edges].

edge_scores

edge_scores(
    row: array,
    col: array,
    a: array,
    b: array,
    scale: float = 1.0,
    *,
    stream=None,
) -> array

Multi-head dot product per edge, the attention scores of graph transformers (e.g. TransformerConv).

out[e, h] = scale * <a[row[e], h], b[col[e], h]>

Equivalent to scale * (a[row] * b[col]).sum(-1) without materialising the two [num_edges, heads, channels] gathers. Differentiable w.r.t. a and b: both gradients are computed with the SpMM kernels.

GPU kernel: one SIMD group per (edge, head), all heads in one launch.

Parameters:

Name Type Description Default
row array

[num_edges] index into a (e.g. the destination node, whose queries are in a).

required
col array

[num_edges] index into b (e.g. the source node, whose keys are in b).

required
a array

[num_a, heads, channels], or [num_a, channels] for one head.

required
b array

[num_b, heads, channels], or [num_b, channels] for one head. num_a and num_b may differ (bipartite graphs).

required
scale float

factor applied to every score, e.g. 1 / sqrt(channels).

1.0

Returns:

Type Description
array

[num_edges, heads] ([num_edges] for 2-D inputs), with the

array

dtype of a.

Source code in mlx_cluster/sparse.py
def edge_scores(
    row: mx.array,
    col: mx.array,
    a: mx.array,
    b: mx.array,
    scale: float = 1.0,
    *,
    stream=None,
) -> mx.array:
    """Multi-head dot product per edge, the attention scores of graph
    transformers (e.g. ``TransformerConv``).

    ``out[e, h] = scale * <a[row[e], h], b[col[e], h]>``

    Equivalent to ``scale * (a[row] * b[col]).sum(-1)`` without materialising
    the two ``[num_edges, heads, channels]`` gathers. Differentiable w.r.t.
    ``a`` and ``b``: both gradients are computed with the SpMM kernels.

    GPU kernel: one SIMD group per (edge, head), all heads in one launch.

    Args:
        row: ``[num_edges]`` index into ``a`` (e.g. the destination node,
            whose queries are in ``a``).
        col: ``[num_edges]`` index into ``b`` (e.g. the source node, whose
            keys are in ``b``).
        a: ``[num_a, heads, channels]``, or ``[num_a, channels]`` for one head.
        b: ``[num_b, heads, channels]``, or ``[num_b, channels]`` for one head.
            ``num_a`` and ``num_b`` may differ (bipartite graphs).
        scale: factor applied to every score, e.g. ``1 / sqrt(channels)``.

    Returns:
        ``[num_edges, heads]`` (``[num_edges]`` for 2-D inputs), with the
        dtype of ``a``.
    """
    if a.ndim != b.ndim or a.ndim not in (2, 3):
        raise ValueError(
            "a and b must both be [num_nodes, heads, channels] or both "
            f"[num_nodes, channels], got shapes {a.shape} and {b.shape}."
        )
    single_head = a.ndim == 2
    if single_head:
        a, b = a[:, None, :], b[:, None, :]
    out = _edge_scores(row, col, a, b, scale=float(scale), stream=stream)
    if single_head:
        out = out[:, 0]
    return out.astype(a.dtype)

gatv2_scores

gatv2_scores(
    row: array,
    col: array,
    x_dst: array,
    x_src: array,
    att: array,
    negative_slope: float = 0.2,
    *,
    csr: Optional[CSR] = None,
    stream=None,
) -> array

GATv2 attention scores (logits, before the softmax), one per edge and head.

out[e, h] = sum_c att[h, c] * leaky_relu(x_src[col[e], h, c] + x_dst[row[e], h, c])

Equivalent to (leaky_relu(x_src[col] + x_dst[row]) * att).sum(-1) without materialising the [num_edges, heads, channels] gathers, in the forward or the backward pass. Differentiable w.r.t. x_dst, x_src and att (not mx.jvp, mx.vmap or second order).

GPU kernels: forward, one SIMD group per (edge, head). Backward, no atomics: one thread per (node, feature) sums the node's edges on the CSR (grad_x_dst) or on its transpose (grad_x_src), deterministic. Hub nodes use the chunked long-row path of spmm_csr() when the CSR has LongRows.

Parameters:

Name Type Description Default
row array

[num_edges] destination node of each edge (edge_index[1]).

required
col array

[num_edges] source node of each edge (edge_index[0]).

required
x_dst array

[num_dst, heads, channels] (or [num_dst, channels]) features of the destination nodes.

required
x_src array

[num_src, heads, channels] (or [num_src, channels]) features of the source nodes.

required
att array

[heads, channels] (or [1, heads, channels], or [channels] for 2-D features) attention vector.

required
negative_slope float

slope of the LeakyReLU for negative inputs.

0.2
csr Optional[CSR]

the CSR of these edges from coo_to_csr() (coo_to_csr(row, col, num_dst, num_cols=num_src)), with its transpose. Only the backward pass uses it. Build it once per graph and pass it; when omitted, it is built on every call (a sort and, for the long rows, a read-back to the host). Edge lists in int32 or int64 are used as they are on the GPU (no per-call conversion).

None

Returns:

Type Description
array

[num_edges, heads] ([num_edges] for 2-D features), with the

array

dtype of x_dst.

Source code in mlx_cluster/sparse.py
def gatv2_scores(
    row: mx.array,
    col: mx.array,
    x_dst: mx.array,
    x_src: mx.array,
    att: mx.array,
    negative_slope: float = 0.2,
    *,
    csr: Optional[CSR] = None,
    stream=None,
) -> mx.array:
    """GATv2 attention scores (logits, before the softmax), one per edge and
    head.

    ``out[e, h] = sum_c att[h, c] * leaky_relu(x_src[col[e], h, c] + x_dst[row[e], h, c])``

    Equivalent to ``(leaky_relu(x_src[col] + x_dst[row]) * att).sum(-1)``
    without materialising the ``[num_edges, heads, channels]`` gathers, in the
    forward or the backward pass. Differentiable w.r.t. ``x_dst``, ``x_src``
    and ``att`` (not ``mx.jvp``, ``mx.vmap`` or second order).

    GPU kernels: forward, one SIMD group per (edge, head). Backward, no
    atomics: one thread per (node, feature) sums the node's edges on the CSR
    (``grad_x_dst``) or on its transpose (``grad_x_src``), deterministic.
    Hub nodes use the chunked long-row path of :func:`spmm_csr` when the CSR
    has :class:`LongRows`.

    Args:
        row: ``[num_edges]`` destination node of each edge (``edge_index[1]``).
        col: ``[num_edges]`` source node of each edge (``edge_index[0]``).
        x_dst: ``[num_dst, heads, channels]`` (or ``[num_dst, channels]``)
            features of the destination nodes.
        x_src: ``[num_src, heads, channels]`` (or ``[num_src, channels]``)
            features of the source nodes.
        att: ``[heads, channels]`` (or ``[1, heads, channels]``, or
            ``[channels]`` for 2-D features) attention vector.
        negative_slope: slope of the LeakyReLU for negative inputs.
        csr: the CSR of these edges from :func:`coo_to_csr`
            (``coo_to_csr(row, col, num_dst, num_cols=num_src)``), with its
            transpose. Only the backward pass uses it. Build it once per graph
            and pass it; when omitted, it is built on every call (a sort and,
            for the long rows, a read-back to the host). Edge lists in int32
            or int64 are used as they are on the GPU (no per-call conversion).

    Returns:
        ``[num_edges, heads]`` (``[num_edges]`` for 2-D features), with the
        dtype of ``x_dst``.
    """
    if x_dst.ndim != x_src.ndim or x_dst.ndim not in (2, 3):
        raise ValueError(
            "x_dst and x_src must both be [num_nodes, heads, channels] or both "
            f"[num_nodes, channels], got shapes {x_dst.shape} and {x_src.shape}."
        )
    single_head = x_dst.ndim == 2
    if single_head:
        x_dst, x_src = x_dst[:, None, :], x_src[:, None, :]
    att = att.reshape(x_dst.shape[1:])
    if csr is None:
        csr = coo_to_csr(row, col, x_dst.shape[0], num_cols=x_src.shape[0])
    if csr.transpose is None:
        raise ValueError(
            "gatv2_scores needs the transposed CSR (coo_to_csr(..., transpose=True))."
        )
    t = csr.transpose
    kwargs = {}
    for prefix, lr in (("", csr.long_rows), ("t_", t.long_rows)):
        if lr is not None:
            kwargs.update(
                {
                    f"{prefix}long_rows": lr.rows,
                    f"{prefix}chunk_ptr": lr.chunk_ptr,
                    f"{prefix}chunk_start": lr.chunk_start,
                    f"{prefix}chunk_end": lr.chunk_end,
                    f"{prefix}long_row_threshold": lr.threshold,
                    f"{prefix}owner": lr.owner,
                }
            )
    # Graph-only arrays precomputed by coo_to_csr, so they are not rebuilt on
    # every call (older CSRs without them still work).
    kwargs["t_edge"] = t.edge
    out = _gatv2_scores(
        row,
        col,
        x_dst,
        x_src,
        att,
        csr.rowptr,
        csr.col,
        csr.perm,
        t.rowptr,
        t.col,
        t.perm,
        negative_slope=float(negative_slope),
        stream=stream,
        **kwargs,
    )
    if single_head:
        out = out[:, 0]
    return out.astype(x_dst.dtype)

build_long_rows

build_long_rows(
    rowptr: array, threshold: int = 256, chunk_size: int = 2048
) -> Optional[LongRows]

Finds rows with more than threshold edges and splits them into chunks of at most chunk_size edges. Returns None if there are none.

Runs once per graph (it reads rowptr back to the host).

Source code in mlx_cluster/sparse.py
def build_long_rows(
    rowptr: mx.array, threshold: int = 256, chunk_size: int = 2048
) -> Optional[LongRows]:
    """Finds rows with more than ``threshold`` edges and splits them into
    chunks of at most ``chunk_size`` edges. Returns ``None`` if there are none.

    Runs once per graph (it reads ``rowptr`` back to the host).
    """
    if threshold < 0 or chunk_size < 1:
        raise ValueError("threshold must be >= 0 and chunk_size >= 1")
    rp = np.array(rowptr, dtype=np.int64)
    deg = np.diff(rp)
    rows = np.nonzero(deg > threshold)[0]
    if rows.size == 0:
        return None
    n_chunks = (deg[rows] + chunk_size - 1) // chunk_size
    chunk_ptr = np.concatenate([[0], np.cumsum(n_chunks)]).astype(np.int64)
    owner = np.repeat(rows, n_chunks)  # long row of each chunk
    local = np.arange(chunk_ptr[-1]) - np.repeat(chunk_ptr[:-1], n_chunks)
    start = rp[owner] + local * chunk_size
    end = np.minimum(start + chunk_size, rp[owner + 1])
    return LongRows(
        rows=mx.array(rows.astype(np.int64)),
        chunk_ptr=mx.array(chunk_ptr),
        chunk_start=mx.array(start.astype(np.int64)),
        chunk_end=mx.array(end.astype(np.int64)),
        threshold=int(threshold),
        owner=mx.array(np.repeat(np.arange(rows.size, dtype=np.int64), n_chunks)),
    )

CSR

Bases: NamedTuple

A sparse matrix in CSR format.

Attributes:

Name Type Description
rowptr array

int64 [num_rows + 1]; row r owns edges rowptr[r]:rowptr[r + 1].

col array

int64 [num_edges] column (source node) of each edge.

values Optional[array]

optional [num_edges] edge weights, in CSR order.

perm array

[num_edges] permutation such that col == input_col[perm]. Use it to reorder any other per-edge array into CSR order.

long_rows Optional[LongRows]

optional LongRows metadata for high-degree rows.

transpose Optional[CSRTranspose]

optional CSRTranspose, used for the backward pass.

CSRTranspose

Bases: NamedTuple

The transpose of a CSR matrix (edges grouped by source node).

Used by spmm_csr() for the backward pass A^T @ grad, so the gradient w.r.t. x also runs on the deterministic, atomic-free CSR kernel. Built by coo_to_csr() (transpose=True).

Attributes:

Name Type Description
rowptr array

int64 [num_cols + 1].

col array

int64 [num_edges] destination (original row) of each edge.

perm array

int64 [num_edges]; transposed edge i is CSR edge perm[i] (used to reorder edge values).

long_rows Optional[LongRows]

optional LongRows for high out-degree nodes.

edge Optional[array]

optional [num_edges]: the original (COO input) index of each transposed edge, CSR.perm[perm] (used by gatv2_scores(); computed on every call when None).

LongRows

Bases: NamedTuple

Load-balancing metadata for CSR rows with many edges.

Rows with more than threshold edges are not handled by the regular one-thread-per-(row, feature) CSR kernel, where a single thread would loop over every edge of a hub node. Instead each such row is cut into chunks of at most chunk_size consecutive edges, each chunk is summed by its own GPU threadgroup, and the chunk sums are added in a fixed order (results stay deterministic). Built by coo_to_csr().

Attributes:

Name Type Description
rows array

int64 [L] ids of the long rows.

chunk_ptr array

int64 [L + 1]; long row l owns chunks chunk_ptr[l]:chunk_ptr[l + 1].

chunk_start array

int64 [K] first edge of each chunk.

chunk_end array

int64 [K] one past the last edge of each chunk.

threshold int

rows with more edges than this are "long".

owner Optional[array]

optional int64 [K]: the long row of each chunk, as an index into rows (used by gatv2_scores(); computed from chunk_ptr when None).