Skip to content

fix: Support zero-length sequences in RNN unrolls - #682

Open
georgeguimaraes wants to merge 1 commit into
elixir-nx:mainfrom
georgeguimaraes:fix/rnn-zero-size-sequences
Open

georgeguimaraes wants to merge 1 commit into
elixir-nx:mainfrom
georgeguimaraes:fix/rnn-zero-size-sequences

Conversation

@georgeguimaraes

@georgeguimaraes georgeguimaraes commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Depends on elixir-nx/nx#1885 and elixir-nx/nx#1886 (zero-size tensors in Nx). Do not merge before an Nx release with zero-size tensors: static_unroll now starts from an empty output, so on Nx 1.0 every static unroll fails. The Nx requirement must go up to that release in the same change.

With zero-size tensors in Nx, an LSTM or GRU over a sequence of length 0 raised an error. The unrolls read the first step to get the output shape, and Nx traces the while body of dynamic_unroll even when it runs 0 times.

  • unroll_initial_zeros runs the cell on one step of zeros.
  • static_unroll starts from an empty output.
  • dynamic_unroll pads the sequence with one spare step that the loop never reads.

Cost: the padding makes a dynamic LSTM about 2% slower on EXLA (40.1 ms to 40.9 ms, batch 32, 128 steps, 256 units).

The unrolls read the first step of the sequence to get the shape of the output, and dynamic_unroll slices one step in its loop body. Nx traces the body even when the loop runs 0 times, so a sequence of length 0 raised an error.

- unroll_initial_zeros runs the cell on one step of zeros, so it does not read the sequence.
- static_unroll starts from an empty output and concatenates the steps.
- dynamic_unroll pads the sequence and the mask with one spare step, so the slices in the loop body are valid for any length. The loop never reads the spare step.
- A scalar mask now covers every step, instead of one column that the slice clamps to.

This needs zero-size tensors in Nx (elixir-nx/nx#1885 and elixir-nx/nx#1886).
@georgeguimaraes
georgeguimaraes marked this pull request as draft October 19, 2026 12:43
@georgeguimaraes
georgeguimaraes marked this pull request as ready for review October 26, 2026 11:58

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.

2 participants