Skip to content

GRUCell

GRUCell(input_dim: int, hidden_dim: int, bias: bool = True)

Bases: Module

A gated recurrent unit cell with the parameters and initialization of torch.nn.GRUCell.

\[ \begin{aligned} r &= \sigma(W_{ir} x + b_{ir} + W_{hr} h + b_{hr}) \\ z &= \sigma(W_{iz} x + b_{iz} + W_{hz} h + b_{hz}) \\ n &= \tanh(W_{in} x + b_{in} + r \odot (W_{hn} h + b_{hn})) \\ h' &= (1 - z) \odot n + z \odot h \end{aligned} \]

Parameters:

Name Type Description Default
input_dim int

Size of the input

required
hidden_dim int

Size of the hidden state

required
bias bool

Whether to use biases. Default: True

True

Methods:

Name Description
reset_parameters

Draws all parameters from \(U(-1/\sqrt{H}, 1/\sqrt{H})\).

__call__

Computes one step.

Source code in mlx_graphs/nn/models/tgn.py
def __init__(self, input_dim: int, hidden_dim: int, bias: bool = True):
    super().__init__()
    self.input_dim = input_dim
    self.hidden_dim = hidden_dim
    self.bias = bias
    self.reset_parameters()

reset_parameters

reset_parameters()

Draws all parameters from \(U(-1/\sqrt{H}, 1/\sqrt{H})\).

Source code in mlx_graphs/nn/models/tgn.py
def reset_parameters(self):
    """Draws all parameters from :math:`U(-1/\\sqrt{H}, 1/\\sqrt{H})`."""
    k = 1.0 / math.sqrt(self.hidden_dim)
    H, D = self.hidden_dim, self.input_dim
    self.weight_ih = mx.random.uniform(-k, k, (3 * H, D))
    self.weight_hh = mx.random.uniform(-k, k, (3 * H, H))
    if self.bias:
        self.bias_ih = mx.random.uniform(-k, k, (3 * H,))
        self.bias_hh = mx.random.uniform(-k, k, (3 * H,))

__call__

__call__(x: array, h: array) -> array

Computes one step.

Parameters:

Name Type Description Default
x array

Inputs, shape [batch, input_dim]

required
h array

Hidden states, shape [batch, hidden_dim]

required

Returns:

Type Description
array

The new hidden states, shape [batch, hidden_dim]

Source code in mlx_graphs/nn/models/tgn.py
def __call__(self, x: mx.array, h: mx.array) -> mx.array:
    """Computes one step.

    Args:
        x: Inputs, shape `[batch, input_dim]`
        h: Hidden states, shape `[batch, hidden_dim]`

    Returns:
        The new hidden states, shape `[batch, hidden_dim]`
    """
    gi = x @ self.weight_ih.T
    gh = h @ self.weight_hh.T
    if self.bias:
        gi = gi + self.bias_ih
        gh = gh + self.bias_hh
    i_r, i_z, i_n = mx.split(gi, 3, axis=-1)
    h_r, h_z, h_n = mx.split(gh, 3, axis=-1)
    r = mx.sigmoid(i_r + h_r)
    z = mx.sigmoid(i_z + h_z)
    n = mx.tanh(i_n + r * h_n)
    return (1 - z) * n + z * h

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