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; |
required |
key
|
array
|
uint32 key with 2 elements,
e.g. |
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 ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple (mlx.core.array, mlx.core.array
|
|
tuple
|
shapes |
tuple
|
|
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 |
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. |
required |
num_nodes_dict
|
Optional[Mapping[NodeType, int]]
|
Optional number of nodes per node type (e.g.
|
None
|
replace
|
bool
|
Sample with replacement. |
False
|
directed
|
bool
|
Only |
True
|
seed
|
Optional[int]
|
Seed for the sampler's RNG. If |
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
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | |
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 |
row |
Dict[EdgeType, array]
|
Per edge type, local index (into |
col |
Dict[EdgeType, array]
|
Per edge type, local index (into |
edge_id |
Dict[EdgeType, array]
|
Per edge type, offset of each sampled edge in
|
num_sampled_nodes |
Dict[NodeType, List[int]]
|
Per node type, |
num_sampled_edges |
Dict[EdgeType, List[int]]
|
Per edge type, |
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]
|
|
required |
metapath
|
Sequence[EdgeType]
|
List of |
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 |
None
|
Returns:
| Type | Description |
|---|---|
MetaPathCSR
|
MetaPathCSR |
Source code in mlx_cluster/metapath.py
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
|
Output of |
required |
start
|
array
|
Start node ids, local to |
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 |
None
|
stream
|
Optional[Stream]
|
Stream or device to run on ( |
None
|
Returns:
| Type | Description |
|---|---|
tuple `(nodes, edges)`
|
|
array
|
local node ids (the type of column |
Tuple[array, array]
|
|
Tuple[array, array]
|
|
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
metapath_node_types
¶
Node type of each of the walk_length + 1 positions of a walk.
Source code in mlx_cluster/metapath.py
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 |
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 |
col_offset |
array
|
Start of each relation inside |
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
|
|
required |
col
|
array
|
|
required |
x
|
array
|
|
required |
values
|
Optional[array]
|
optional |
None
|
num_rows
|
Optional[int]
|
number of output rows. Defaults to |
None
|
reduce
|
SpMMReduce
|
how the messages |
'sum'
|
Returns:
| Type | Description |
|---|---|
array
|
|
Source code in mlx_cluster/sparse.py
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
|
|
required |
col
|
array
|
|
required |
x
|
array
|
|
required |
values
|
Optional[array]
|
optional |
None
|
reduce
|
SpMMReduce
|
how the messages |
'sum'
|
long_rows
|
Optional[LongRows]
|
optional |
None
|
transpose
|
Optional[CSRTranspose]
|
optional |
None
|
Returns:
| Type | Description |
|---|---|
array
|
|
Source code in mlx_cluster/sparse.py
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 |
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 |
True
|
num_cols
|
Optional[int]
|
number of columns (source nodes), i.e. |
None
|
Source code in mlx_cluster/sparse.py
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 |
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
|
|
required |
col
|
array
|
|
required |
a
|
array
|
|
required |
b
|
array
|
|
required |
scale
|
float
|
factor applied to every score, e.g. |
1.0
|
Returns:
| Type | Description |
|---|---|
array
|
|
array
|
dtype of |
Source code in mlx_cluster/sparse.py
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
|
|
required |
col
|
array
|
|
required |
x_dst
|
array
|
|
required |
x_src
|
array
|
|
required |
att
|
array
|
|
required |
negative_slope
|
float
|
slope of the LeakyReLU for negative inputs. |
0.2
|
csr
|
Optional[CSR]
|
the CSR of these edges from |
None
|
Returns:
| Type | Description |
|---|---|
array
|
|
array
|
dtype of |
Source code in mlx_cluster/sparse.py
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 | |
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
CSR
¶
Bases: NamedTuple
A sparse matrix in CSR format.
Attributes:
| Name | Type | Description |
|---|---|---|
rowptr |
array
|
|
col |
array
|
|
values |
Optional[array]
|
optional |
perm |
array
|
|
long_rows |
Optional[LongRows]
|
optional |
transpose |
Optional[CSRTranspose]
|
optional |
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
|
|
col |
array
|
|
perm |
array
|
|
long_rows |
Optional[LongRows]
|
optional |
edge |
Optional[array]
|
optional |
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
|
|
chunk_ptr |
array
|
|
chunk_start |
array
|
|
chunk_end |
array
|
|
threshold |
int
|
rows with more edges than this are "long". |
owner |
Optional[array]
|
optional |