Rank error in tf.nn.dynamic_rnn
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
A rank error in tf.nn.dynamic_rnn almost always means one of the tensors has the wrong number of dimensions. The most common problem is the input tensor: dynamic_rnn expects a 3-D input shaped like batch, time, and features, but many bugs feed it a 2-D matrix or a tensor with the axes in the wrong order.
What dynamic_rnn Expects
tf.nn.dynamic_rnn is a TensorFlow 1.x style API for recurrent models. Its core input is usually shaped as:
- '
[batch_size, max_time, feature_dim]whentime_major=False' - '
[max_time, batch_size, feature_dim]whentime_major=True'
That means rank 3, not rank 2.
A minimal working example using the compatibility API looks like this:
If inputs were shaped [None, feature_dim], TensorFlow would complain because the time dimension is missing.
The Most Common Rank Mistake
A lot of code starts from tabular data shaped like [batch_size, feature_dim] and tries to feed it directly into an RNN. That is not enough information for a sequence model, because there is no explicit time axis.
Wrong idea:
Corrected idea for sequences of length 1:
Or, if you already have a 2-D tensor and want to add a time dimension deliberately:
Now x_3d has shape [batch_size, 1, feature_dim], which satisfies the rank requirement.
time_major=True Changes Axis Order
Another source of rank or shape confusion is time_major=True. The input is still rank 3, but the first two axes swap roles.
If you enable time_major=True, your input should look like [time, batch, features]. Many bugs happen when developers set time_major=True for performance reasons but keep feeding [batch, time, features] tensors.
sequence_length Has Its Own Shape Rule
The sequence_length argument must be a rank-1 vector with one length per batch element.
If you accidentally pass a scalar, matrix, or incorrectly broadcasted tensor, dynamic_rnn can fail with a rank or shape error that looks unrelated at first glance.
A full example:
The batch size of sequence_length must match the batch size of inputs.
Debug Shapes Before Running the Session
When working with TensorFlow 1.x style graphs, it helps to inspect static shapes early.
If the shape is partially dynamic, inspect runtime shapes too:
When a rank error appears, the fastest path is usually to verify:
- input rank is 3
- feature dimension matches what the cell expects
- '
sequence_lengthrank is 1' - '
time_majormatches the actual tensor layout'
If You Are Using Modern TensorFlow
If you are writing new code, prefer tf.keras.layers.LSTM, GRU, or SimpleRNN. They hide much of the low-level shape handling that made dynamic_rnn error-prone.
The same rank principle still applies, but the API surface is easier to reason about.
Common Pitfalls
The biggest pitfall is feeding a 2-D tensor into an API that expects a 3-D sequence tensor.
Another common issue is mixing up batch-major and time-major layouts after enabling time_major=True.
Developers also often forget that sequence_length is a rank-1 vector, not a scalar or matrix.
Finally, dynamic_rnn is a legacy API. If you are starting new work, use Keras recurrent layers unless you have a specific reason to stay with TensorFlow 1.x graph code.
Summary
- '
tf.nn.dynamic_rnnexpects a rank-3 input tensor.' - The usual shape is
[batch, time, features]unlesstime_major=Trueis enabled. - '
sequence_lengthmust be a rank-1 vector with one value per batch item.' - Add a time axis explicitly if your data starts as rank 2.
- For new TensorFlow code, prefer Keras RNN layers over legacy
dynamic_rnn.
Related reading
- RBM implementation with tensorflow
- Read big train/validation/test datasets in tensorflow
- Recurrentshop and Keras multi-dimensional `RNN` results in a dimensions mismatch error
- reduce size of pretrained deep learning model for feature generation
- Re-implementing TF 1.0 sampled_softmax_loss funtion for seq2seq model in to TF 2 Keras model
- Re-initialize variables in Tensorflow
- Rank mismatch Rank of labels received 2 should equal rank of logits minus 1 received 2
- Rasa NLU Confidence \`Score\` Computation
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.