Skip to content

TemporalEncoding

TemporalEncoding(out_features_dim: int)

Bases: Module

The time encoding from the "Do We Really Need Complicated Model Architectures for Temporal Networks?" paper, as PyG's TemporalEncoding.

Each entry is mapped to a vector with exponentially decreasing frequencies, projected to \([-1, 1]\) by a cosine:

\[ y_{i} = \cos \left(x \cdot \sqrt{d}^{-(i - 1)/\sqrt{d}} \right) \]

for \(1 \leq i \leq d\).

Parameters:

Name Type Description Default
out_features_dim int

Size \(d\) of each output sample.

required

Example:

import mlx.core as mx
from mlx_graphs.nn import TemporalEncoding

encoder = TemporalEncoding(16)
>>> encoder(mx.array([0.0, 10.0, 200.0])).shape
(3, 16)

Methods:

Name Description
__call__

Encodes x (any shape, flattened) into an array of shape

Source code in mlx_graphs/nn/encoding.py
def __init__(self, out_features_dim: int):
    super().__init__()
    self.out_features_dim = out_features_dim
    sqrt = math.sqrt(out_features_dim)
    self.weight = (
        1.0 / mx.power(sqrt, mx.linspace(0, sqrt, out_features_dim))
    ).reshape(1, -1)
    self.freeze(keys=["weight"], recurse=False)

__call__

__call__(x: array) -> array

Encodes x (any shape, flattened) into an array of shape [x.size, out_features_dim].

Source code in mlx_graphs/nn/encoding.py
def __call__(self, x: mx.array) -> mx.array:
    """Encodes ``x`` (any shape, flattened) into an array of shape
    ``[x.size, out_features_dim]``."""
    # elementwise product: a K=1 matmul is less accurate on the GPU
    return mx.cos(x.reshape(-1, 1) * self.weight)

from mlx_graphs.nn import TemporalEncoding · mlx_graphs/nn/encoding.py