8000 Fix RNN final carry with seq_lengths and multiple batch dims by bhaskargurram-ai · Pull Request #5650 · google/flax · GitHub
[go: up one dir, main page]

Skip to content

Fix RNN final carry with seq_lengths and multiple batch dims - #5650

Open
bhaskargurram-ai wants to merge 1 commit into
google:mainfrom
bhaskargurram-ai:fix/rnn-last-carry-multi-batch
Open

bhaskargurram-ai wants to merge 1 commit into
google:mainfrom
bhaskargurram-ai:fix/rnn-last-carry-multi-batch

Conversation

@bhaskargurram-ai
Copy link
Copy Markdown

What does this PR do?

RNN (linen and nnx) documents inputs of shape (*batch, time, *features) and seq_lengths of shape (*batch), but _select_last_carry gathered the last valid carry with x[last_idx, jnp.arange(x.shape[1])], which only covers one batch axis. With two or more batch dimensions and return_carry=True, the call either raised a broadcasting error (batch axes of different sizes) or silently returned a carry with an extra axis taken from the wrong sequences (batch axes of equal size).

The fix indexes every batch axis with jnp.indices(seq_lengths.shape, sparse=True). For a single batch axis this is the same as before.

Tests: test_numerical_equivalence_with_mask_multiple_batch_dims (linen, batch (3, 3), compares each final carry with stepping the cell by hand) and test_rnn_with_seq_lengths_multiple_batch_dims (nnx, batch (2, 3), compares with running each sequence on its own). Both fail on main and pass with this change. tests/linen/linen_recurrent_test.py and tests/nnx/nn/recurrent_test.py pass.

Checklist

_select_last_carry indexed the stacked carries with
x[last_idx, jnp.arange(x.shape[1])], which only works for a single batch
axis. With inputs of shape (*batch, time, features) and seq_lengths of
shape (*batch), as documented, it either raised a broadcasting error or,
when the batch axes had equal sizes, returned a carry with an extra axis
built from the wrong sequences. Index every batch axis instead, in both
the linen and nnx RNN.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RNN returns a wrong final carry (or raises) with seq_lengths and more than one batch dimension

1 participant

0