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

[JAX] Add an option to control the out-of-bounds indexing behavior of Haiku embedding layers. #493

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
6 changes: 5 additions & 1 deletion haiku/_src/embed.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ def __call__(
ids: jnp.ndarray,
lookup_style: Optional[Union[str, hk.EmbedLookupStyle]] = None,
precision: Optional[jax.lax.Precision] = None,
out_of_bounds_mode: Optional[str] = None
) -> jnp.ndarray:
r"""Lookup embeddings.

Expand All @@ -150,6 +151,8 @@ def __call__(
ids: integer array.
lookup_style: Overrides the ``lookup_style`` given in the constructor.
precision: Overrides the ``precision`` given in the constructor.
out_of_bounds_mode: Overrides the out-of-bounds indexing behavior for
gathers.

Returns:
Tensor of ``ids.shape + [embedding_dim]``.
Expand All @@ -176,7 +179,8 @@ def __call__(
# indexing with DeviceArray, while indexing with numpy.ndarray works fine.
# See https://github.com/google/jax/issues/620 for more details.
# Cast to a jnp array in case `ids` is a tracer (eg un a dynamic_unroll).
return jnp.asarray(self.embeddings)[(ids,)]
return (jnp.asarray(self.embeddings)
.at[(ids,)].get(mode=out_of_bounds_mode))

elif lookup_style == hk.EmbedLookupStyle.ONE_HOT:
one_hot_ids = jax.nn.one_hot(ids, self.vocab_size)
Expand Down