1. Sequential Data¶
Unlike MLPs and CNNs which process fixed-size inputs, sequential data requires modeling temporal or positional dependencies.
| Task | Input | Output | Example |
|---|---|---|---|
| Time series prediction | Sequence | Scalar | Stock price forecasting |
| Sequence-to-sequence | Sequence | Sequence | Machine translation |
| Audio-to-text | Sequence | Sequence | Speech recognition |
| Image-to-text | Image | Sequence | Image captioning |
2. Recurrent Neural Networks (RNN)¶
Basic RNN Architecture¶
For a sequence , the RNN maintains a hidden state that carries information from previous time steps:
where is typically:
The same parameters are shared across all time steps.
Allows processing variable-length inputs.
Computation is sequential (not parallelizable).
Training: Backpropagation Through Time (BPTT)¶
The total loss over a sequence of length :
Gradients flow backward through the unrolled computational graph. For long sequences, this requires storing all hidden states.
Truncated BPTT: Carry hidden states forward in time forever, but only backpropagate for a smaller number of steps.
Vanishing and Exploding Gradients¶
The gradient with respect to involves repeated multiplications by and derivatives of :
Since :
Gradient vanishing: The product of many small terms becomes extremely small, limiting the network’s ability to capture long-range dependencies.
Gradient exploding: If the largest singular value of is large, the product grows exponentially.
Mitigation:
Gradient exploding gradient clipping.
Gradient vanishing architectural modifications (LSTM, GRU).
3. Long Short-Term Memory (LSTM)¶
Introduced by Hochreiter and Schmidhuber (1997) to address vanishing gradients.
LSTM Cell Equations¶
At each time step, the LSTM maintains a cell state (long-term memory) and a hidden state (short-term output):
Forget gate:
Input gate:
Candidate cell state:
Cell state update:
Output gate:
Hidden state:
where denotes element-wise multiplication.
Key Properties¶
Gated structure: The forget gate controls what information to discard; the input gate controls what new information to store.
Additive updates: The cell state is updated by addition (), which helps preserve gradients over long sequences.
Mitigates (but does not completely eliminate) vanishing/exploding gradients.
Widely adopted in deep learning around 2013–2015.
4. Gated Recurrent Units (GRU)¶
A simpler variant introduced by Cho et al. (2014):
Reset gate:
Update gate:
Candidate hidden state:
Hidden state:
Similar to LSTM but with fewer parameters (lacks a separate output gate and cell state).
Often comparable performance to LSTM with less computation.
5. Limitations of RNNs¶
| Limitation | Description |
|---|---|
| Long-term dependencies | Still struggle with very long sequences due to vanishing gradients |
| Limited parallelization | Sequential processing prevents parallel computation, leading to slower training |
These limitations motivated the development of the Transformer architecture.
6. Attention Mechanism¶
Core Idea¶
The goal of attention is to transform input token representations into richer representations where each output depends on all tokens:
where and are attention coefficients.
Self-Attention¶
Idea: Measure similarity between tokens and convert into probabilities via softmax.
Matrix form: Stack outputs into :
where softmax is applied row-wise. Each row of sums to 1.
Trainable Self-Attention (Scaled Dot-Product)¶
Introduce learnable linear transformations:
where and .
Query (): The token seeking information.
Key (): What each token offers.
Value (): The actual information content.
Scaling by : Prevents large inner products from producing unstable gradients.
Multi-Head Attention¶
Different tokens may have different types of relationships. Use parallel attention heads:
Concatenate and apply an output transformation:
Usually so the output dimension matches the input.
7. Attention Masks¶
Without restriction, token may attend to all tokens . We need to restrict invalid interactions.
Definition¶
Introduce mask matrix :
where:
Since , blocked positions receive zero attention weight.
Padding Mask¶
In a mini-batch, sequences have different lengths. Shorter sequences are padded. Padded tokens should not affect the output.
Define padding indicator where if position is padding. Then:
Causal Mask¶
In autoregressive modeling (next-token prediction), token must not attend to future tokens :
The -th row can only place attention mass on positions . Both masks are combined: .
8. Computational Complexity of Attention¶
| Step | Complexity |
|---|---|
| Score matrix | |
| Softmax + storage | time, memory |
| Output | |
| Overall | — quadratic in sequence length |
This quadratic complexity is a key bottleneck for very long sequences.
9. Transformer Architecture¶
Tokenization and Embedding¶
Tokenization: Convert text into tokens . Use subword tokenization (e.g., BPE) to balance vocabulary size and sequence length.
Embedding: Map each token to a vector where is a learned embedding matrix and is a one-hot vector.
Positional Encoding¶
Since self-attention processes tokens as a set (order-agnostic), we inject positional information:
where is a position encoding vector. This can be either learned or fixed (e.g., sinusoidal).
Transformer Layer¶
A transformer layer combines four components:
Multi-head self-attention
Residual connection
Normalization
Feed-forward network (MLP)
Post-Norm (original Transformer):
Pre-Norm (modern LLMs like GPT, LLaMA):
Pre-Norm is more stable for very deep networks.
Layer Normalization (LayerNorm)¶
For a token representation :
where are learnable scale and shift parameters. Normalizes each token independently (across the feature dimension).
RMS Normalization (RMSNorm)¶
Simpler alternative without mean centering:
Only scaling, no shifting.
Fewer parameters, more efficient.
Used in modern architectures like LLaMA.
10. Decoder-Only Transformer¶
Used in GPT, LLaMA, etc.:
Stack multiple masked transformer layers.
Each layer uses causal self-attention.
Add embedding layer at input and projection + softmax at output for next-token prediction.
The key insight of the Transformer (Vaswani et al., 2017) is that attention is all you need — recurrence and convolutions can be entirely replaced by attention mechanisms, enabling greater parallelization and faster training.