API Reference for `RNN` and Seq2Seq models in tensorflow
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
TensorFlow provides recurrent neural network (RNN) layers through tf.keras.layers — SimpleRNN, LSTM, and GRU. For sequence-to-sequence (Seq2Seq) models, you build an encoder-decoder architecture by stacking RNN layers with return_state=True on the encoder and feeding the encoder's final state into the decoder. TensorFlow 2.x uses Keras as the primary API, and the legacy tf.nn.dynamic_rnn and tf.contrib.seq2seq APIs are removed. Modern Seq2Seq implementations use the functional or subclassing API with attention mechanisms from tf.keras.layers.Attention or tfa.seq2seq.
SimpleRNN
SimpleRNN applies the recurrence h_t = tanh(W_x * x_t + W_h * h_{t-1} + b). It suffers from vanishing gradients on long sequences — use LSTM or GRU for sequences longer than 20-30 timesteps.
LSTM (Long Short-Term Memory)
LSTM adds a cell state that carries information across many timesteps via gating mechanisms (forget gate, input gate, output gate). return_state=True returns both the hidden state and the cell state, which is essential for initializing the Seq2Seq decoder.
GRU (Gated Recurrent Unit)
GRU has two gates (reset and update) instead of LSTM's three, making it faster to train with fewer parameters. Performance is often similar to LSTM — try both and compare on your dataset.
Seq2Seq Encoder-Decoder
The encoder processes the input sequence and produces a context vector (final hidden state). The decoder uses this context to generate the output sequence one timestep at a time. During training, "teacher forcing" feeds the true previous token as decoder input.
Seq2Seq with Attention
Attention allows the decoder to focus on different parts of the encoder output at each timestep, rather than relying on a single fixed-length context vector. This dramatically improves performance on longer sequences.
Inference (Prediction) Loop
Common Pitfalls
- Not setting
return_sequences=Truewhen stacking RNN layers: Each RNN layer expects a 3D input(batch, timesteps, features). Withoutreturn_sequences=True, the layer outputs 2D(batch, features), and the next RNN layer raises a shape error. Only the final RNN layer in a stack can usereturn_sequences=False. - Using
recurrent_dropout > 0with CuDNN: TensorFlow's CuDNN-optimized LSTM/GRU kernels do not supportrecurrent_dropout. Setting it falls back to the slower non-CuDNN implementation without warning. Use regulardropoutfor GPU training or accept the performance cost. - Forgetting teacher forcing during training: The Seq2Seq decoder must receive the ground truth previous token during training (teacher forcing). Feeding the decoder's own predictions during training causes slow convergence because early predictions are random noise.
- Ignoring sequence padding and masking: Variable-length sequences must be padded and masked so the model does not learn from padding tokens. Use
tf.keras.layers.Maskingor passmask_zero=Trueto the embedding layer, and ensure downstream layers propagate the mask. - Using legacy
tf.nn.dynamic_rnnortf.contrib.seq2seq: These APIs are removed in TensorFlow 2.x. Usetf.keras.layers.LSTM/GRUwithreturn_state=Truefor encoders and the functional API for Seq2Seq architectures. For beam search decoding, usetfa.seq2seq.BeamSearchDecoderfrom TensorFlow Addons.
Summary
- Use
tf.keras.layers.LSTMorGRUfor recurrent layers —SimpleRNNsuffers from vanishing gradients - Set
return_sequences=Truewhen stacking RNN layers; usereturn_state=Truefor Seq2Seq encoders - Build Seq2Seq by passing encoder final states as
initial_stateto the decoder LSTM - Add
tf.keras.layers.Attentionbetween encoder and decoder for better long-sequence performance - Use
Bidirectionalwrapper for tasks where future context matters (classification, NER) - During inference, run the decoder one step at a time in a loop, feeding each output as the next input
Related reading
- Apply function for every pair of elements in two Tensors in Tensorflow
- Applying callbacks in a custom training loop in Tensorflow 2.0
- Appropriate Deep Learning Structure for multi-class classification
- Appropriate Deep Learning Structure for multi-class classification
- Apply TensorFlow Transform to transform/scale features in production
- Are tf.layers.dense and tf.contrib.layers.fully_connected interchangeable?
- Application of neural network for use with log file data
- Applying machine learning to a guessing game?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the 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.