Skip to content

PositionalEncoding

PositionalEncoding(
    out_features_dim: int, base_freq: float = 0.0001, granularity: float = 1.0
)

Bases: Module

The sinusoidal positional encoding from the "Attention Is All You Need" paper, as PyG's PositionalEncoding.

\[ PE(x)_{2 \cdot i} &= \sin(x / 10000^{2 \cdot i / d}) \\ PE(x)_{2 \cdot i + 1} &= \cos(x / 10000^{2 \cdot i / d}) \]

where \(x\) is the position and \(i\) the dimension. As in PyG, the output is ordered as all the sines followed by all the cosines.

Parameters:

Name Type Description Default
out_features_dim int

Size \(d\) of each output sample (even).

required
base_freq float

Base frequency of the sinusoids. Default: 1e-4

0.0001
granularity float

Granularity of the positions: smaller values capture finer changes in positions. Default: 1.0

1.0

Example:

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

encoder = PositionalEncoding(16)
>>> encoder(mx.array([0.0, 1.0, 2.5])).shape
(3, 16)

Methods:

Name Description
__call__

Encodes the positions x (any shape, flattened) into an array

Source code in mlx_graphs/nn/encoding.py
def __init__(
    self,
    out_features_dim: int,
    base_freq: float = 1e-4,
    granularity: float = 1.0,
):
    super().__init__()
    if out_features_dim % 2 != 0:
        raise ValueError(
            "Cannot use sinusoidal positional encoding with odd "
            f"'out_features_dim' (got {out_features_dim})."
        )
    self.out_features_dim = out_features_dim
    self.base_freq = base_freq
    self.granularity = granularity
    self.frequency = mx.power(
        base_freq, mx.linspace(0, 1, out_features_dim // 2)
    ).astype(mx.float32)
    self.freeze(keys=["frequency"], recurse=False)

__call__

__call__(x: array) -> array

Encodes the positions 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 the positions ``x`` (any shape, flattened) into an array
    of shape ``[x.size, out_features_dim]``."""
    if self.granularity != 1.0:
        x = x / self.granularity
    out = x.reshape(-1, 1) * self.frequency.reshape(1, -1)
    return mx.concatenate([mx.sin(out), mx.cos(out)], axis=-1)

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