Skip to content

TGNMemory

TGNMemory(
    num_nodes: int,
    raw_msg_dim: int,
    memory_dim: int,
    time_dim: int,
    message_module: Callable,
    aggregator_module: Callable,
)

Bases: Module

The Temporal Graph Network (TGN) memory model from the "Temporal Graph Networks for Deep Learning on Dynamic Graphs" paper, as PyG's torch_geometric.nn.TGNMemory.

Every node has a memory vector, updated with a GRU cell from the messages of the events it takes part in. The events of a mini-batch are stored as raw messages by update_state() and only turned into memory updates when the nodes are next accessed, so that the memory read for a mini-batch never contains information from that mini-batch itself.

In training mode, memory(n_id) computes the memory of n_id updated with the pending messages (differentiable w.r.t. the message modules, the time encoder and the GRU), and update_state() first writes those updates to the state and then stores the new messages. In evaluation mode, memory(n_id) returns the stored memory and update_state() applies the new messages right away. Switching from training to evaluation mode (.eval() / .train(False), on this module or on a model containing it) flushes all pending messages into the memory, as in PyG.

The state is not part of parameters() (see the design notes of mlx_graphs.nn.models.tgn): read it with memory and last_update. In particular, save_weights() / load_weights only save and restore the learnable parameters, not the memory (PyG's state_dict also holds the memory and last_update buffers). To checkpoint them, use memory_state() and load_memory_state(), e.g. mx.savez("memory.npz", **memory.memory_state()). As with PyG's buffers, the pending messages are not part of it.

Timestamps are integers (int64, as PyG's TemporalData.t).

Parameters:

Name Type Description Default
num_nodes int

Number of nodes to keep a memory for

required
raw_msg_dim int

Size of the raw messages (event features)

required
memory_dim int

Size of the memory

required
time_dim int

Size of the time encoding

required
message_module Callable

Message function, called as message_module(z_src, z_dst, raw_msg, t_enc), with an out_features_dim (or PyG's out_channels) attribute, e.g. IdentityMessage

required
aggregator_module Callable

Aggregation of the messages of each node, called as aggregator_module(msg, index, t, dim_size), e.g. LastAggregator or MeanAggregator

required

Example:

import mlx.core as mx
from mlx_graphs.nn import TGNMemory
from mlx_graphs.nn.models.tgn import IdentityMessage, LastAggregator

memory = TGNMemory(
    num_nodes=100,
    raw_msg_dim=16,
    memory_dim=32,
    time_dim=32,
    message_module=IdentityMessage(16, 32, 32),
    aggregator_module=LastAggregator(),
)
n_id = mx.array([0, 1, 2])
z, last_update = memory(n_id)  # [3, 32], [3]
memory.update_state(src, dst, t, msg)  # after computing the loss
memory.detach()

Methods:

Name Description
reset_parameters

Re-initializes all learnable parameters and resets the state.

reset_state

Resets the memory, the last update times and the message stores.

memory_state

The memory state as arrays, the equivalent of PyG's memory

load_memory_state

Restores a state returned by memory_state() (e.g. read back

detach

Detaches the memory from gradient computation (and evaluates it).

__call__

Returns the current memory and last update time of the nodes n_id

update_state

Updates the state with the new events (src, dst, t, raw_msg).

Attributes:

Name Type Description
memory array

The memory of all nodes, shape [num_nodes, memory_dim].

last_update array

The time of the last memory update of every node, shape

Source code in mlx_graphs/nn/models/tgn.py
def __init__(
    self,
    num_nodes: int,
    raw_msg_dim: int,
    memory_dim: int,
    time_dim: int,
    message_module: Callable,
    aggregator_module: Callable,
):
    super().__init__()
    self.num_nodes = num_nodes
    self.raw_msg_dim = raw_msg_dim
    self.memory_dim = memory_dim
    self.time_dim = time_dim

    self.msg_s_module = message_module
    self.msg_d_module = copy.deepcopy(message_module)
    self.aggr_module = aggregator_module
    self.time_enc = TimeEncoder(time_dim)
    self.gru = GRUCell(_out_dim(message_module), memory_dim)

    self._assoc = np.zeros(num_nodes, dtype=np.int64)
    self._msg_s_store = _MessageStore(num_nodes, raw_msg_dim)
    self._msg_d_store = _MessageStore(num_nodes, raw_msg_dim)
    self.reset_parameters()

memory property

memory: array

The memory of all nodes, shape [num_nodes, memory_dim].

last_update property

last_update: array

The time of the last memory update of every node, shape [num_nodes].

reset_parameters

reset_parameters()

Re-initializes all learnable parameters and resets the state.

Source code in mlx_graphs/nn/models/tgn.py
def reset_parameters(self):
    """Re-initializes all learnable parameters and resets the state."""
    for module in (self.msg_s_module, self.msg_d_module, self.aggr_module):
        if hasattr(module, "reset_parameters"):
            module.reset_parameters()
    self.time_enc.reset_parameters()
    self.gru.reset_parameters()
    self.reset_state()

reset_state

reset_state()

Resets the memory, the last update times and the message stores.

Source code in mlx_graphs/nn/models/tgn.py
def reset_state(self):
    """Resets the memory, the last update times and the message stores."""
    self._memory = mx.zeros((self.num_nodes, self.memory_dim))
    self._last_update = np.zeros(self.num_nodes, dtype=np.int64)
    self._reset_message_store()

memory_state

memory_state() -> dict

The memory state as arrays, the equivalent of PyG's memory and last_update buffers in state_dict: a dict with "memory" ([num_nodes, memory_dim]) and "last_update" ([num_nodes], int64).

Source code in mlx_graphs/nn/models/tgn.py
def memory_state(self) -> dict:
    """The memory state as arrays, the equivalent of PyG's ``memory``
    and ``last_update`` buffers in ``state_dict``: a dict with
    ``"memory"`` (``[num_nodes, memory_dim]``) and ``"last_update"``
    (``[num_nodes]``, int64)."""
    return {"memory": self._memory, "last_update": self.last_update}

load_memory_state

load_memory_state(state: dict)

Restores a state returned by memory_state() (e.g. read back with mx.load). The pending messages are cleared.

Parameters:

Name Type Description Default
state dict

A dict with "memory" and "last_update".

required
Source code in mlx_graphs/nn/models/tgn.py
def load_memory_state(self, state: dict):
    """Restores a state returned by :meth:`memory_state` (e.g. read back
    with ``mx.load``). The pending messages are cleared.

    Args:
        state: A dict with ``"memory"`` and ``"last_update"``.
    """
    memory = mx.array(state["memory"]).astype(mx.float32)
    last_update = _host_time(state["last_update"])
    if memory.shape != (self.num_nodes, self.memory_dim):
        raise ValueError(
            f"memory has shape {memory.shape}, expected "
            f"{(self.num_nodes, self.memory_dim)}"
        )
    if last_update.shape != (self.num_nodes,):
        raise ValueError(
            f"last_update has shape {last_update.shape}, expected "
            f"{(self.num_nodes,)}"
        )
    self._memory = memory
    self._last_update = last_update.copy()
    self._reset_message_store()

detach

detach()

Detaches the memory from gradient computation (and evaluates it).

Source code in mlx_graphs/nn/models/tgn.py
def detach(self):
    """Detaches the memory from gradient computation (and evaluates it)."""
    self._memory = mx.stop_gradient(self._memory)
    mx.eval(self._memory)

__call__

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

Returns the current memory and last update time of the nodes n_id (with the pending messages applied in training mode).

Parameters:

Name Type Description Default
n_id IndexLike

Node indices, shape [n]

required

Returns:

Type Description
array

The memory, shape [n, memory_dim], and the last update times,

array

shape [n].

Source code in mlx_graphs/nn/models/tgn.py
def __call__(self, n_id: IndexLike) -> Tuple[mx.array, mx.array]:
    """Returns the current memory and last update time of the nodes ``n_id``
    (with the pending messages applied in training mode).

    Args:
        n_id: Node indices, shape `[n]`

    Returns:
        The memory, shape `[n, memory_dim]`, and the last update times,
        shape `[n]`.
    """
    n_id = _host(n_id)
    if self.training:
        return self._get_updated_memory(n_id)
    memory = self._memory[mx.array(n_id.astype(np.int32))]
    return memory, mx.array(self._last_update[n_id])

update_state

update_state(src: IndexLike, dst: IndexLike, t: IndexLike, raw_msg: array)

Updates the state with the new events (src, dst, t, raw_msg).

Parameters:

Name Type Description Default
src IndexLike

Source nodes, shape [num_events]

required
dst IndexLike

Destination nodes, shape [num_events]

required
t IndexLike

Integer timestamps, shape [num_events] (as PyG's int64 TemporalData.t; floating arrays must hold integer values, otherwise a ValueError is raised instead of truncating them)

required
raw_msg array

Raw messages, shape [num_events, raw_msg_dim]

required
Source code in mlx_graphs/nn/models/tgn.py
def update_state(
    self, src: IndexLike, dst: IndexLike, t: IndexLike, raw_msg: mx.array
):
    """Updates the state with the new events ``(src, dst, t, raw_msg)``.

    Args:
        src: Source nodes, shape `[num_events]`
        dst: Destination nodes, shape `[num_events]`
        t: Integer timestamps, shape `[num_events]` (as PyG's int64
            ``TemporalData.t``; floating arrays must hold integer values,
            otherwise a ``ValueError`` is raised instead of truncating
            them)
        raw_msg: Raw messages, shape `[num_events, raw_msg_dim]`
    """
    src, dst, t = _host(src), _host(dst), _host_time(t)
    raw_msg = np.asarray(np.array(raw_msg), dtype=np.float32)
    raw_msg = raw_msg.reshape(src.size, self.raw_msg_dim)
    n_id = np.unique(np.concatenate([src, dst]))

    if self.training:
        self._update_memory(n_id)
        self._msg_s_store.update(src, dst, t, raw_msg)
        self._msg_d_store.update(dst, src, t, raw_msg)
    else:
        self._msg_s_store.update(src, dst, t, raw_msg)
        self._msg_d_store.update(dst, src, t, raw_msg)
        self._update_memory(n_id)

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