Repository navigation
Fix RNN final carry with seq_lengths and multiple batch dims - #5650
Open
bhaskargurram-ai wants to merge 1 commit into
Open
bhaskargurram-ai wants to merge 1 commit into
bhaskargurram-ai wants to merge 1 commit into
Conversation
_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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What does this PR do?
RNN(linen and nnx) documents inputs of shape(*batch, time, *features)andseq_lengthsof shape(*batch), but_select_last_carrygathered the last valid carry withx[last_idx, jnp.arange(x.shape[1])], which only covers one batch axis. With two or more batch dimensions andreturn_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) andtest_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.pyandtests/nnx/nn/recurrent_test.pypass.Checklist