Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Recurrent Neural Networks and Transformers

1. Sequential Data

Unlike MLPs and CNNs which process fixed-size inputs, sequential data requires modeling temporal or positional dependencies.

TaskInputOutputExample
Time series predictionSequenceScalarStock price forecasting
Sequence-to-sequenceSequenceSequenceMachine translation
Audio-to-textSequenceSequenceSpeech recognition
Image-to-textImageSequenceImage captioning

2. Recurrent Neural Networks (RNN)

Basic RNN Architecture

For a sequence (x1,x2,…,xT)(x_1, x_2, \dots, x_T), the RNN maintains a hidden state hth_t that carries information from previous time steps:

ht=fW(ht−1,xt),y^t=gW′(ht)h_t = f_W(h_{t-1}, x_t), \quad \hat{y}_t = g_{W'}(h_t)

where fWf_W is typically:

ht=tanh⁡(Whhht−1+Wxhxt+bh)h_t = \tanh(W_{hh} h_{t-1} + W_{xh} x_t + b_h)

Training: Backpropagation Through Time (BPTT)

The total loss over a sequence of length TT:

E(θ)=1T∑t=1TL(yt,y^t)E(\theta) = \frac{1}{T} \sum_{t=1}^{T} L(y_t, \hat{y}_t)

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 hth_t involves repeated multiplications by Whh⊤W_{hh}^\top and derivatives of tanh⁡\tanh:

∂hT∂ht=∏τ=t+1TWhh⊤ diag(tanh⁡′(⋅))\frac{\partial h_T}{\partial h_t} = \prod_{\tau=t+1}^{T} W_{hh}^\top \, \text{diag}\bigl(\tanh'(\cdot)\bigr)

Since tanh⁡′∈[0,1]\tanh' \in [0, 1]:

Mitigation:


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 CtC_t (long-term memory) and a hidden state hth_t (short-term output):

Forget gate: ft=σ(Wf⋅[ht−1,xt]+bf)f_t = \sigma(W_f \cdot [h_{t-1}, x_t] + b_f)

Input gate: it=σ(Wi⋅[ht−1,xt]+bi)i_t = \sigma(W_i \cdot [h_{t-1}, x_t] + b_i)

Candidate cell state: C~t=tanh⁡(WC⋅[ht−1,xt]+bC)\tilde{C}_t = \tanh(W_C \cdot [h_{t-1}, x_t] + b_C)

Cell state update: Ct=ft⊙Ct−1+it⊙C~tC_t = f_t \odot C_{t-1} + i_t \odot \tilde{C}_t

Output gate: ot=σ(Wo⋅[ht−1,xt]+bo)o_t = \sigma(W_o \cdot [h_{t-1}, x_t] + b_o)

Hidden state: ht=ot⊙tanh⁡(Ct)h_t = o_t \odot \tanh(C_t)

where ⊙\odot denotes element-wise multiplication.

Key Properties


4. Gated Recurrent Units (GRU)

A simpler variant introduced by Cho et al. (2014):

Reset gate: rt=σ(Wr⋅[ht−1,xt])r_t = \sigma(W_r \cdot [h_{t-1}, x_t])

Update gate: zt=σ(Wz⋅[ht−1,xt])z_t = \sigma(W_z \cdot [h_{t-1}, x_t])

Candidate hidden state: h~t=tanh⁡(W⋅[rt⊙ht−1,xt])\tilde{h}_t = \tanh(W \cdot [r_t \odot h_{t-1}, x_t])

Hidden state: ht=(1−zt)⊙ht−1+zt⊙h~th_t = (1 - z_t) \odot h_{t-1} + z_t \odot \tilde{h}_t


5. Limitations of RNNs

LimitationDescription
Long-term dependenciesStill struggle with very long sequences due to vanishing gradients
Limited parallelizationSequential 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 {x1,…,xn}\{x_1, \dots, x_n\} into richer representations {y1,…,yn}\{y_1, \dots, y_n\} where each output depends on all tokens:

yi=∑j=1naijxjy_i = \sum_{j=1}^{n} a_{ij} x_j

where aij≥0a_{ij} \ge 0 and ∑j=1naij=1\sum_{j=1}^{n} a_{ij} = 1 are attention coefficients.

Self-Attention

Idea: Measure similarity between tokens and convert into probabilities via softmax.

aij=exp⁡(xi⊤xj)∑j′=1nexp⁡(xi⊤xj′)a_{ij} = \frac{\exp(x_i^\top x_j)}{\sum_{j'=1}^{n} \exp(x_i^\top x_{j'})}

Matrix form: Stack outputs into Y∈Rn×dY \in \mathbb{R}^{n \times d}:

A=softmax(XX⊤),Y=AXA = \text{softmax}(XX^\top), \quad Y = AX

where softmax is applied row-wise. Each row of AA sums to 1.

Trainable Self-Attention (Scaled Dot-Product)

Introduce learnable linear transformations:

Q=XW(q),K=XW(k),V=XW(v)Q = XW^{(q)}, \quad K = XW^{(k)}, \quad V = XW^{(v)}

where W(q),W(k)∈Rd×dkW^{(q)}, W^{(k)} \in \mathbb{R}^{d \times d_k} and W(v)∈Rd×dvW^{(v)} \in \mathbb{R}^{d \times d_v}.

attention(Q,K,V)=softmax(QK⊤dk)V\text{attention}(Q, K, V) = \text{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right) V

Multi-Head Attention

Different tokens may have different types of relationships. Use HH parallel attention heads:

Hh=attention(Qh,Kh,Vh),h=1,…,HH_h = \text{attention}(Q_h, K_h, V_h), \quad h = 1, \dots, H

Concatenate and apply an output transformation:

Y=[H1,…,HH]W(o)Y = [H_1, \dots, H_H] W^{(o)}

Usually H⋅dv=dH \cdot d_v = d so the output dimension matches the input.


7. Attention Masks

Without restriction, token ii may attend to all tokens j=1,…,nj = 1, \dots, n. We need to restrict invalid interactions.

Definition

Introduce mask matrix M∈Rnq×nkM \in \mathbb{R}^{n_q \times n_k}:

attention(Q,K,V;M)=softmax(QK⊤dk+M)V\text{attention}(Q, K, V; M) = \text{softmax}\left(\frac{QK^\top}{\sqrt{d_k}} + M\right) V

where:

Mij={0,allowed−∞,blockedM_{ij} = \begin{cases} 0, & \text{allowed} \\ -\infty, & \text{blocked} \end{cases}

Since exp⁡(−∞)=0\exp(-\infty) = 0, 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 pj∈{0,1}p_j \in \{0, 1\} where pj=1p_j = 1 if position jj is padding. Then:

Mijpad={−∞,pj=10,pj=0M^{\text{pad}}_{ij} = \begin{cases} -\infty, & p_j = 1 \\ 0, & p_j = 0 \end{cases}

Causal Mask

In autoregressive modeling (next-token prediction), token ii must not attend to future tokens j>ij > i:

Mijcausal={0,j≤i−∞,j>iM^{\text{causal}}_{ij} = \begin{cases} 0, & j \le i \\ -\infty, & j > i \end{cases}

The ii-th row can only place attention mass on positions j≤ij \le i. Both masks are combined: M=Mcausal+MpadM = M^{\text{causal}} + M^{\text{pad}}.


8. Computational Complexity of Attention

StepComplexity
Score matrix S=QK⊤S = QK^\topO(n2d)O(n^2 d)
Softmax + storageO(n2)O(n^2) time, O(n2)O(n^2) memory
Output Y=softmax(S)VY = \text{softmax}(S)VO(n2d)O(n^2 d)
OverallO(n2d)O(n^2 d) — quadratic in sequence length nn

This quadratic complexity is a key bottleneck for very long sequences.


9. Transformer Architecture

Tokenization and Embedding

Positional Encoding

Since self-attention processes tokens as a set (order-agnostic), we inject positional information:

x~i=xi+pi\tilde{x}_i = x_i + p_i

where pip_i is a position encoding vector. This can be either learned or fixed (e.g., sinusoidal).

Transformer Layer

A transformer layer combines four components:

  1. Multi-head self-attention

  2. Residual connection

  3. Normalization

  4. Feed-forward network (MLP)

Post-Norm (original Transformer):

Z=Norm(Y(X)+X),X=Norm(MLP(Z)+Z)Z = \text{Norm}(Y(X) + X), \quad X = \text{Norm}(\text{MLP}(Z) + Z)

Pre-Norm (modern LLMs like GPT, LLaMA):

Z=Y(Norm(X))+X,X=MLP(Norm(Z))+Z)Z = Y(\text{Norm}(X)) + X, \quad X = \text{MLP}(\text{Norm}(Z)) + Z)

Pre-Norm is more stable for very deep networks.

Layer Normalization (LayerNorm)

For a token representation x=[x1,…,xd]x = [x_1, \dots, x_d]:

μ=1d∑i=1dxi,σ=1d∑i=1d(xi−μ)2\mu = \frac{1}{d} \sum_{i=1}^{d} x_i, \quad \sigma = \sqrt{\frac{1}{d} \sum_{i=1}^{d} (x_i - \mu)^2}
x^i=xi−μσ,yi=γix^i+βi\hat{x}_i = \frac{x_i - \mu}{\sigma}, \quad y_i = \gamma_i \hat{x}_i + \beta_i

where γ,β\gamma, \beta are learnable scale and shift parameters. Normalizes each token independently (across the feature dimension).

RMS Normalization (RMSNorm)

Simpler alternative without mean centering:

RMS(x)=1d∑i=1dxi2+ϵ,x^i=xiRMS(x),yi=γix^i\text{RMS}(x) = \sqrt{\frac{1}{d} \sum_{i=1}^{d} x_i^2 + \epsilon}, \quad \hat{x}_i = \frac{x_i}{\text{RMS}(x)}, \quad y_i = \gamma_i \hat{x}_i

10. Decoder-Only Transformer

Used in GPT, LLaMA, etc.:

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.