Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add reset_gate flag to MGUCell. #3760

Merged
merged 1 commit into from
Mar 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions flax/linen/recurrent.py
Original file line number Diff line number Diff line change
Expand Up @@ -635,6 +635,16 @@ class MGUCell(RNNCellBase):

where x is the input and h is the output of the previous time step.

If ``reset_gate`` is false, the above becomes

.. math::

\begin{array}{ll}
f = \sigma(W_{if} x + b_{if} + W_{hf} h) \\
n = \tanh(W_{in} x + b_{in} + W_{hn} h) \\
h' = (1 - f) * n + f * h \\
\end{array}

Example usage::

>>> import flax.linen as nn
Expand Down Expand Up @@ -663,6 +673,7 @@ class MGUCell(RNNCellBase):
output (default: initializers.zeros_init()).
dtype: the dtype of the computation (default: None).
param_dtype: the dtype passed to parameter initializers (default: float32).
reset_gate: flag for applying reset gating.
"""

features: int
Expand All @@ -675,6 +686,7 @@ class MGUCell(RNNCellBase):
dtype: Optional[Dtype] = None
param_dtype: Dtype = jnp.float32
carry_init: Initializer = initializers.zeros_init()
reset_gate: bool = True

@compact
def __call__(self, carry, inputs):
Expand Down Expand Up @@ -713,10 +725,12 @@ def __call__(self, carry, inputs):
dense_i(name='if', bias_init=self.forget_bias_init)(inputs)
+ dense_h(name='hf')(h)
)
# add bias because the linear transformations aren't directly summed.
# add bias when the linear transformations aren't directly summed.
x = dense_h(name="hn", use_bias=self.reset_gate)(h)
if self.reset_gate:
x *= f
n = self.activation_fn(
dense_i(name='in', bias_init=self.activation_bias_init)(inputs)
+ f * dense_h(name='hn', use_bias=True)(h)
dense_i(name="in", bias_init=self.activation_bias_init)(inputs) + x
)
new_h = (1.0 - f) * n + f * h
return new_h, new_h
Expand Down
Loading