Recurrent Neural Networks (RNN) • Backpropagation Through Time (BPTT) • Mathematical Derivations of Vanishing & Exploding Gradients • Gradient Clipping • Long Short-Term Memory (LSTM) Internal Gate Mechanics (Forget, Input, Candidate Cell, Output Gates, Constant Error Carousel) • Gated Recurrent Units (GRU) • Bidirectional Encoders (BiLSTM) • Sequence-to-Sequence (Seq2Seq) Architecture & Information Bottleneck • Bahdanau Additive Attention vs. Luong Multiplicative Attention • The Transformer Architecture (Vaswani et al. 2017) • Scaled Dot-Product Self-Attention • Multi-Head Attention (MHA) • Sinusoidal Positional Encoding Formulations • Encoder & Decoder LayerNorm and Residual Connections • Pretrained Language Models: BERT (MLM, NSP, Bidirectionality), GPT (Autoregressive Decoder), RoBERTa, T5, BART • 15 Solved University Examination Questions.
An Elman RNN processes sequential inputs $\mathbf{x}_1, \dots, \mathbf{x}_T$ by updating a continuous hidden state $\mathbf{h}_t$:
$$\mathbf{\mathbf{h}_t = \tanh(\mathbf{W}_{hh} \mathbf{h}_{t-1} + \mathbf{W}_{xh} \mathbf{x}_t + \mathbf{b}_h) \qquad \mathbf{\hat{y}}_t = \text{softmax}(\mathbf{W}_{hy} \mathbf{h}_t + \mathbf{b}_y)}$$When backpropagating loss $\mathcal{L}_T$ back to step $t$, the gradient chain rule involves repeated matrix multiplications:
$$\mathbf{\frac{\partial \mathcal{L}_T}{\partial \mathbf{h}_t} = \frac{\partial \mathcal{L}_T}{\partial \mathbf{h}_T} \prod_{k=t+1}^T \frac{\partial \mathbf{h}_k}{\partial \mathbf{h}_{k-1}} = \frac{\partial \mathcal{L}_T}{\partial \mathbf{h}_T} \prod_{k=t+1}^T \mathbf{W}_{hh}^T \text{diag}(1 - \tanh^2(\mathbf{z}_k))}$$Because $\tanh'(z) = 1 - \tanh^2(z) \le 1.0$, if the maximum eigenvalue $\lambda_{\text{max}}(\mathbf{W}_{hh}) < 1$, the product $\prod_{k=t+1}^T \mathbf{W}_{hh}^T \rightarrow 0$ exponentially as sequence length $T - t > 10$, destroying long-range dependencies! If $\lambda_{\text{max}} > 1$, gradients explode ($\rightarrow \infty$).
Hochreiter & Schmidhuber (1997) introduced the LSTM, which introduces an explicit linear memory cell state $\mathbf{C}_t$ governed by three multiplicative gates:
Why LSTM Prevents Vanishing Gradients: The derivative $\frac{\partial \mathbf{C}_t}{\partial \mathbf{C}_{t-1}} = \mathbf{f}_t$. If the forget gate is saturated at $\mathbf{f}_t \approx 1$, error gradients flow backward through time with zero exponential decay!
The Transformer completely replaces recurrence with pure attention mechanisms, enabling massive parallelization across all tokens during training.
Given Query ($\mathbf{Q}$), Key ($\mathbf{K}$), and Value ($\mathbf{V}$) matrices projected from input embeddings:
$$\mathbf{\text{Attention}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{softmax}\left( \frac{\mathbf{Q} \mathbf{K}^T}{\sqrt{d_k}} \right) \mathbf{V}}$$Scaling Factor $\frac{1}{\sqrt{d_k}}$: For large projection dimensions $d_k$, the dot products grow large in magnitude, pushing the softmax function into regions with vanishingly small gradients. Scaling by $\sqrt{d_k}$ stabilizes variance to unit magnitude.
Allows the model to jointly attend to information from different representation subspaces at different positions:
$$\mathbf{\text{MultiHead}(\mathbf{Q}, \mathbf{K}, \mathbf{V}) = \text{Concat}(\text{head}_1, \dots, \text{head}_h) \mathbf{W}^O}$$ $$\text{where } \text{head}_i = \text{Attention}(\mathbf{Q}\mathbf{W}_i^Q, \ \mathbf{K}\mathbf{W}_i^K, \ \mathbf{V}\mathbf{W}_i^V)$$Because self-attention is permutation-invariant, positional information must be injected via deterministic sinusoids:
$$\mathbf{PE_{(pos, 2i)} = \sin\left( \frac{pos}{10000^{2i / d_{\text{model}}}} \right) \qquad PE_{(pos, 2i+1)} = \cos\left( \frac{pos}{10000^{2i / d_{\text{model}}}} \right)}$$| Dimension | BERT (Devlin et al. 2018) | GPT Series (Radford et al. 2018–2023) |
|---|---|---|
| Architecture | Encoder-Only: Full bidirectional self-attention across all positions. | Decoder-Only: Causal masked self-attention (tokens attend only to prior positions). |
| Pretraining Objective | Masked Language Model (MLM 15%) + Next Sentence Prediction (NSP). | Autoregressive Next-Token Prediction: $\max_\theta \sum \log P(x_i \mid x_{ |
| Ideal Tasks | NLU: Text classification, NER, extractive QA, sentence similarity. | NLG: Open-ended generation, creative writing, dialogue, in-context zero/few-shot reasoning. |
| Attention Type | Alignment Score Function $\text{score}(\mathbf{s}_i, \mathbf{h}_j)$ | Computational Efficiency |
|---|---|---|
| Bahdanau Additive Attention | $$\text{score}(\mathbf{s}_i, \mathbf{h}_j) = \mathbf{v}_a^T \tanh(\mathbf{W}_a \mathbf{s}_i + \mathbf{U}_a \mathbf{h}_j)$$ | Requires single hidden layer feed-forward network; higher parameter count. |
| Luong Multiplicative (General) | $$\text{score}(\mathbf{s}_i, \mathbf{h}_j) = \mathbf{s}_i^T \mathbf{W}_a \mathbf{h}_j$$ | Matrix multiplication; highly optimized on GPU tensor cores. |
| Luong Dot Product | $$\text{score}(\mathbf{s}_i, \mathbf{h}_j) = \mathbf{s}_i^T \mathbf{h}_j$$ | Zero parameters; requires decoder and encoder hidden states to have identical dimensions. |
| Model Family | Architectural Paradigm | Pretraining Objective | Typical Downstream Use-Cases |
|---|---|---|---|
| BERT / RoBERTa / DeBERTa | Encoder-Only (Bidirectional self-attention) | Masked Language Modeling (MLM 15%) + Disentangled Attention | Classification, Token Tagging (NER), Extractive QA (SQuAD), Sentence Embeddings. |
| GPT Series (1–4) / LLaMA / Mistral | Decoder-Only (Causal autoregressive masked attention) | Next-Token Autoregressive Prediction $\sum \log P(x_t \mid x_{| Open-ended text generation, In-context zero/few-shot reasoning, Conversational AI. |
|
| T5 / BART | Encoder-Decoder (Full cross-attention) | Span Corruption / Denoising Autoencoding sequence-to-sequence | Abstractive text summarization, Machine translation, Text re-writing. |
Given Transformer model dimension $d_{\text{model}} = 512$, number of attention heads $h = 8$, sequence length $T = 64$:
In Computer Vision, Batch Normalization normalizes across batch dimension $N$ for each channel. In NLP, sentence lengths vary widely and mini-batches contain padded tokens:
Prove why the dot product $\mathbf{q} \cdot \mathbf{k} = \sum_{i=1}^{d_k} q_i k_i$ has variance $d_k$ under independent zero-mean unit-variance components:
For sequence length $n$ and representation dimension $d$:
In LoRA (Hu et al. 2021), the pretrained weight matrix $\mathbf{W}_0 \in \mathbb{R}^{d \times k}$ is frozen, and weight updates $\Delta \mathbf{W}$ are decomposed into low-rank matrices $\mathbf{B} \in \mathbb{R}^{d \times r}$ and $\mathbf{A} \in \mathbb{R}^{r \times k}$ ($r \ll \min(d, k)$):
$$\mathbf{\mathbf{h} = \mathbf{W}_0 \mathbf{x} + \Delta \mathbf{W} \mathbf{x} = \mathbf{W}_0 \mathbf{x} + \frac{\alpha}{r} \mathbf{B} \mathbf{A} \mathbf{x}}$$Reduces trainable fine-tuning parameters by up to 99.9% (e.g., from 7 billion to 4 million parameters) with zero inference latency overhead (weights are folded into $\mathbf{W} = \mathbf{W}_0 + \frac{\alpha}{r}\mathbf{BA}$)!
Prove that for any fixed offset $k$, $PE_{(pos + k)}$ can be represented as a linear function of $PE_{(pos)}$:
$$\sin(\omega (pos + k)) = \sin(\omega \cdot pos)\cos(\omega \cdot k) + \cos(\omega \cdot pos)\sin(\omega \cdot k)$$ $$\cos(\omega (pos + k)) = \cos(\omega \cdot pos)\cos(\omega \cdot k) - \sin(\omega \cdot pos)\sin(\omega \cdot k)$$ $$\mathbf{\begin{bmatrix} PE_{(pos+k, 2i)} \\ PE_{(pos+k, 2i+1)} \end{bmatrix} = \begin{bmatrix} \cos(\omega_i k) & \sin(\omega_i k) \\ -\sin(\omega_i k) & \cos(\omega_i k) \end{bmatrix} \begin{bmatrix} PE_{(pos, 2i)} \\ PE_{(pos, 2i+1)} \end{bmatrix}}}$$Conclusion: The self-attention mechanism can effortlessly learn to attend by relative token positions via linear projection!
Dao et al. (2022) observed that standard GPU self-attention is bounded by High Bandwidth Memory (HBM) read/write memory bandwidth rather than FLOPs. FlashAttention tiles the $Q, K, V$ matrices into SRAM cache blocks, performing online softmax normalization without writing the massive $N \times N$ attention matrix to HBM, speeding up training by up to $\mathbf{4\times}$ while cutting memory from $O(N^2)$ to $O(N)$!
RoPE (Su et al. 2021) encodes positional information directly into Query and Key vectors via complex 2D rotation matrices $\mathbf{R}_{\Theta, m}^d$, preserving relative distance under dot-product attention: $\langle \mathbf{R}_m \mathbf{q}, \mathbf{R}_n \mathbf{k} \rangle = g(\mathbf{q}, \mathbf{k}, m - n)$. Standard in modern LLMs (LLaMA, Mistral)!
To reduce KV-Cache memory consumption in large-scale LLMs (LLaMA-2/3, Mistral):
Standard LLM inference is memory bandwidth-bound. Speculative Decoding (Leviathan et al. 2023) uses a fast small Draft Model (e.g., 1B parameters) to generate $K$ speculative draft tokens in parallel, which are verified simultaneously in a single forward pass by the large Target Model (e.g., 70B parameters), achieving a $\mathbf{2\times \text{ to } 3\times}$ inference acceleration with zero mathematical difference in output probability distribution!
For a standard 12-layer BERT-base model ($d_{\text{model}} = 768, h = 12, d_{\text{ff}} = 3072, |V| = 30522$):
In MoE Transformers (Mixtral 8x7B), each token selects top $k=2$ out of $E=8$ expert FFN networks via routing gate $G(x) = \text{Softmax}(\text{TopK}(x \cdot W_g, k))$, achieving $8\times$ capacity with $2\times$ active FLOPs!
Prove why the geometric progression of wavelengths $\lambda_i = 2\pi \cdot 10000^{2i/d}$ spans from $2\pi$ to $20000\pi$, allowing the model to attend simultaneously to immediate neighboring tokens and global document-level structural anchors!
Show that without the $\frac{1}{\sqrt{d_k}}$ scaling factor, the variance of dot product $q \cdot k$ equals $d_k = 64$, pushing softmax outputs to saturated extremes ($0.0$ or $1.0$) with near-zero gradients!
For output loss $\mathcal{L}$, the gradient with respect to Value weight matrix $\mathbf{W}^V$ is $\frac{\partial \mathcal{L}}{\partial \mathbf{W}^V} = \mathbf{X}^T \mathbf{A}^T \frac{\partial \mathcal{L}}{\partial \mathbf{Y}}$ where $\mathbf{A} = \text{softmax}(QK^T/\sqrt{d_k})$.
Show that $\mathbf{R}_{\Theta, m}^T \mathbf{R}_{\Theta, n} = \mathbf{R}_{\Theta, n-m}$, proving that the attention score between query at position $m$ and key at position $n$ depends purely on relative distance $n-m$!
Prove that linear projection into $h$ distinct lower-dimensional subspaces $\mathbb{R}^{d_k}$ allows distinct heads to attend simultaneously to different syntactic relations (e.g., Head 1 attends to Direct Objects, Head 2 attends to Prepositional Attachments, Head 3 attends to Coreferent Pronouns)!
In RoPE Linear Scaling (Chen et al. 2023), to extend an LLM from 4k context length to 32k context ($8\times$ scaling), rotation angles $\theta_i$ are divided by scale factor $s = 8$: $\tilde{\theta}_i = \theta_i / 8$, preserving frequency dynamics within the pretrained attention kernel!
Let SRAM cache size be $M$. Set block sizes $B_r = \lceil M / (4 d) \rceil, B_c = \lceil M / (4 d) \rceil$. FlashAttention loads blocks $Q_i \in \mathbb{R}^{B_r \times d}$ and $K_j \in \mathbb{R}^{B_c \times d}$ into SRAM, computing local attention without GPU DRAM roundtrips!
In Transformer Decoders: Query matrix $\mathbf{Q} \in \mathbb{R}^{T_{\text{dec}} \times d}$ comes from the decoder hidden states, while Key $\mathbf{K} \in \mathbb{R}^{T_{\text{enc}} \times d}$ and Value $\mathbf{V} \in \mathbb{R}^{T_{\text{enc}} \times d}$ come from encoder representations. The resulting attention matrix $\mathbf{A} \in \mathbb{R}^{T_{\text{dec}} \times T_{\text{enc}}}$ aligns each generated word with relevant source words!
Show that $\mathbf{p}_i \cdot \mathbf{p}_j = \sum_{k=1}^{d/2} \cos(\omega_k (i - j))$, proving that the attention similarity between any two positional vectors depends purely on relative distance $|i - j|$!
In modern LLMs (LLaMA-3, Mistral), standard ReLU is replaced with SwiGLU: $\text{SwiGLU}(x) = \text{Swish}(x W_1) \otimes (x W_3) W_2$ where $\text{Swish}(z) = z \cdot \sigma(\beta z)$, delivering a $1.2\%$ boost on MMLU benchmarks!
Dao (2023) redesigned FlashAttention loop nesting by swapping the outer loop to iterate over sequence blocks of $Q$, reducing non-matmul FLOPs and boosting tensor core utilization from $50\%$ to $\mathbf{73\%}$ on Nvidia A100/H100 GPUs!
Press et al. (2022) replaced positional embeddings with fixed linear slope biases $m = 2^{-8i/h}$: $\text{softmax}(QK^T/\sqrt{d_k} - m \cdot |i - j|)$, training on 2048 tokens while extrapolating to $\mathbf{8192+}$ tokens with zero perplexity increase!
In RoBERTa, duplicating the corpus 10 times and applying 10 independent random 15% masks avoids training on identical static masks across 40 epochs!
The small scalar $\epsilon = 10^{-5}$ prevents division-by-zero during backpropagation when token activation variance across hidden units collapses to zero!
For sequence length $L = 4096$, batch size $B = 1$, 80 layers, $d_{\text{model}} = 8192$, FP16 format:
$$\text{KV-Size} = 2 \times (\text{layers}) \times (\text{seq\_len}) \times (\text{hidden\_dim}) \times 2 \text{ bytes} = 2 \times 80 \times 4096 \times 8192 \times 2 \approx \mathbf{10.73 \text{ GB RAM!}}$$For source sequence length $M$ and target translation length $N$, cross-attention matrix $\mathbf{A} \in \mathbb{R}^{N \times M}$ computes in $O(N \cdot M \cdot d)$ time, fully parallelizable across all target time steps during training!
Pretraining BERT requires 4 days on 64 TPU chips across 3.3 billion words. Fine-tuning on downstream GLUE classification tasks converges in $< 3$ epochs within 15 minutes on a single standard consumer GPU!
Prove that wavelengths form a geometric progression from $2\pi$ to $10000 \cdot 2\pi$, allowing self-attention to resolve both adjacent syntactic token bindings and distant cross-paragraph anaphora!
In LLaMA-3 70B with $h = 64$ query heads and $G = 8$ KV groups, GQA reduces KV-cache memory bandwidth consumption by $\mathbf{8\times}$, allowing $8\times$ larger batch sizes during generation!
For batch size $B$, sequence length $N$, hidden dimension $d$, and number of heads $h$: $\mathbf{Q} \mathbf{K}^T$ computes in $O(B \cdot h \cdot N^2 \cdot \frac{d}{h}) = \mathbf{O(B \cdot N^2 \cdot d)}$ operations. Highly parallelizable across all GPU CUDA thread cores!