How to add attention layer to a Bi-LSTM
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
Adding attention to a Bi-LSTM usually means asking the model to learn which time steps in the sequence matter most before making its final prediction. The core requirement is simple: the Bi-LSTM must return a sequence of hidden states, and the attention block must turn that sequence into a weighted context vector.
What Changes When You Add Attention
A plain Bi-LSTM for classification often looks like this:
- embedding or feature input
- '
Bidirectional(LSTM(...))' - dense output layer
Without attention, many models use only the final hidden representation. With attention, the model keeps the full sequence of hidden states and learns weights over time steps.
That means the Bi-LSTM must use return_sequences=True.
A Small Attention Layer in Keras
One practical way to add attention is to define a custom attention layer that scores each time step, normalizes the scores with softmax, and returns the weighted sum.
This layer expects input shaped like batch x timesteps x features and produces a context vector shaped like batch x features.
Building a Bi-LSTM with Attention
Here is a runnable text-classification style model using that attention layer:
The crucial part is return_sequences=True. If you forget that, the LSTM returns only one vector and there is no time-axis information for attention to weight.
A Minimal Training Example
To make the structure concrete, here is a small synthetic training run:
This is not a meaningful dataset, but it is enough to verify that the model compiles and trains end to end.
How the Attention Weights Work
The attention layer computes a score for each Bi-LSTM time step. Those scores are normalized so they sum to 1 across the sequence. The output context vector is then the weighted combination of all hidden states.
The effect is:
- highly relevant time steps get larger weights
- less relevant time steps still contribute, but less
- the downstream dense layers receive a summary focused on important positions
This often works better than relying only on the final hidden state, especially when important evidence may appear anywhere in the sequence.
Functional API Version
If you want more control, the Functional API is usually better than Sequential, especially when you later want to inspect attention outputs or branch the model.
This version is often easier to extend to multi-class classification or to expose intermediate tensors for debugging.
Built-In Attention Layers vs Custom Attention
Keras also provides built-in attention-related layers, but a custom layer is often easier to understand when you are starting out. It makes the sequence scoring and weighted sum explicit.
Once the concept is clear, you can decide whether a built-in attention mechanism or a more advanced architecture such as self-attention is a better fit for the task.
Common Pitfalls
The most common mistake is forgetting return_sequences=True on the Bi-LSTM, which removes the time dimension that attention needs. Another is applying attention directly to token ids or embeddings before the recurrent layer when the intent was to weigh contextual hidden states. Developers also sometimes mix binary and multi-class output configurations, such as pairing a sigmoid output with categorical loss. A final issue is expecting attention to solve a weak data pipeline automatically; it can improve representation learning, but it does not replace correct preprocessing, padding, and label setup.
Summary
- To add attention to a Bi-LSTM, keep the full sequence output from the recurrent layer.
- Attention learns weights over time steps and produces a context vector.
- '
return_sequences=Trueis required for the Bi-LSTM.' - A custom attention layer is a clear way to understand the mechanism in Keras.
- Match the final output layer and loss function to the real prediction task.
Related reading
- How to add Dropout in Keras functional model?
- How to add regularizations in TensorFlow?
- how to add text preprocessing tokenization step into Tensorflow model
- How to apply data augmentation in TensorFlow 2.0 after tfds.load
- How to add basic authentication for Tensorflow serving
- How to add if condition in a TensorFlow graph?
- How to apply gradient clipping in TensorFlow?
- How to apply gradient clipping in TensorFlow?
.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.