Skip to content

LastNeighborLoader

LastNeighborLoader(num_nodes: int, size: int)

Keeps, for every node, its size most recent neighbors in an ever-growing (undirected) temporal graph, as PyG's torch_geometric.nn.models.tgn.LastNeighborLoader.

The state is kept on the host (NumPy); the returned arrays are MLX arrays.

Parameters:

Name Type Description Default
num_nodes int

Number of nodes

required
size int

Number of most recent neighbors to keep per node

required

Example:

from mlx_graphs.nn.models.tgn import LastNeighborLoader

loader = LastNeighborLoader(num_nodes=10, size=5)
loader.insert(mx.array([0, 1]), mx.array([2, 3]))
n_id, edge_index, e_id = loader(mx.array([0, 3]))
# edge_index (in the local indexing of `n_id`) points from the
# neighbors to the nodes, e_id are the events of the edges

Methods:

Name Description
__call__

Returns the most recent neighborhood of the nodes n_id.

insert

Inserts new events (in time order) into the temporal graph.

reset_state

Removes all the inserted events.

Source code in mlx_graphs/nn/models/tgn.py
def __init__(self, num_nodes: int, size: int):
    self.num_nodes = num_nodes
    self.size = size
    self.neighbors = np.zeros((num_nodes, size), dtype=np.int64)
    self.e_id = np.full((num_nodes, size), -1, dtype=np.int64)
    self._assoc = np.zeros(num_nodes, dtype=np.int64)
    self.reset_state()

__call__

__call__(n_id: IndexLike) -> Tuple[array, array, array]

Returns the most recent neighborhood of the nodes n_id.

Parameters:

Name Type Description Default
n_id IndexLike

Node indices

required

Returns:

Type Description
array

The sorted unique nodes of the neighborhood (n_id and their

array

neighbors), the [2, num_edges] edges from neighbors to nodes

array

in the local indexing of these nodes, and the event index of every

Tuple[array, array, array]

edge.

Source code in mlx_graphs/nn/models/tgn.py
def __call__(self, n_id: IndexLike) -> Tuple[mx.array, mx.array, mx.array]:
    """Returns the most recent neighborhood of the nodes ``n_id``.

    Args:
        n_id: Node indices

    Returns:
        The sorted unique nodes of the neighborhood (``n_id`` and their
        neighbors), the ``[2, num_edges]`` edges from neighbors to nodes
        in the local indexing of these nodes, and the event index of every
        edge.
    """
    n_id = _host(n_id)
    neighbors = self.neighbors[n_id]
    nodes = np.repeat(n_id.reshape(-1, 1), self.size, axis=1)
    e_id = self.e_id[n_id]

    # Filter invalid neighbors (identified by `e_id < 0`).
    mask = e_id >= 0
    neighbors, nodes, e_id = neighbors[mask], nodes[mask], e_id[mask]

    # Relabel node indices.
    n_id = np.unique(np.concatenate([n_id, neighbors]))
    self._assoc[n_id] = np.arange(n_id.size)
    neighbors, nodes = self._assoc[neighbors], self._assoc[nodes]

    edge_index = np.stack([neighbors, nodes]).astype(np.int32)
    return (
        mx.array(n_id.astype(np.int32)),
        mx.array(edge_index),
        mx.array(e_id.astype(np.int32)),
    )

insert

insert(src: IndexLike, dst: IndexLike)

Inserts new events (in time order) into the temporal graph.

Parameters:

Name Type Description Default
src IndexLike

Source nodes, shape [num_events]

required
dst IndexLike

Destination nodes, shape [num_events]

required
Source code in mlx_graphs/nn/models/tgn.py
def insert(self, src: IndexLike, dst: IndexLike):
    """Inserts new events (in time order) into the temporal graph.

    Args:
        src: Source nodes, shape `[num_events]`
        dst: Destination nodes, shape `[num_events]`
    """
    src, dst = _host(src), _host(dst)

    # Central nodes, their neighbors and the current event ids.
    neighbors = np.concatenate([src, dst])
    nodes = np.concatenate([dst, src])
    e_id = np.tile(np.arange(self.cur_e_id, self.cur_e_id + src.size), 2)
    self.cur_e_id += src.size

    # Locations of the new interactions in a dense [num_nodes, size] format.
    perm = np.argsort(nodes, kind="stable")
    nodes, neighbors, e_id = nodes[perm], neighbors[perm], e_id[perm]

    n_id = np.unique(nodes)
    self._assoc[n_id] = np.arange(n_id.size)

    dense_id = np.arange(nodes.size) % self.size
    dense_id += self._assoc[nodes] * self.size

    dense_e_id = np.full(n_id.size * self.size, -1, dtype=np.int64)
    dense_e_id[dense_id] = e_id
    dense_e_id = dense_e_id.reshape(-1, self.size)

    dense_neighbors = np.zeros(n_id.size * self.size, dtype=np.int64)
    dense_neighbors[dense_id] = neighbors
    dense_neighbors = dense_neighbors.reshape(-1, self.size)

    # Merge the old and new interactions and keep the most recent ones.
    e_id = np.concatenate([self.e_id[n_id], dense_e_id], axis=-1)
    neighbors = np.concatenate([self.neighbors[n_id], dense_neighbors], axis=-1)
    perm = np.argsort(-e_id, axis=-1, kind="stable")[:, : self.size]
    self.e_id[n_id] = np.take_along_axis(e_id, perm, axis=-1)
    self.neighbors[n_id] = np.take_along_axis(neighbors, perm, axis=-1)

reset_state

reset_state()

Removes all the inserted events.

Source code in mlx_graphs/nn/models/tgn.py
def reset_state(self):
    """Removes all the inserted events."""
    self.cur_e_id = 0
    self.e_id.fill(-1)

from mlx_graphs.nn.models.tgn import LastNeighborLoader · mlx_graphs/nn/models/tgn.py