Classical NLP to Attention: Guide to Sequence Modeling
Natural Language Processing (NLP) has undergone a massive paradigm shift over the past decade. We have moved from handcrafted rule-based systems and statistical frequencies to complex sequential architectures, culminating in the attention-driven models that power modern Large Language Models (LLMs).
1. Statistical vs. Deep NLP
Before deep learning took over, text processing relied heavily on statistical methods.
Statistical NLP
Statistical NLP treats text as collections of words or n-grams. It relies on probability distributions and token frequencies without explicitly modeling underlying grammatical structures.
Key Techniques: Bag-of-Words (BoW), TF-IDF (Term Frequency-Inverse Document Frequency), Naive Bayes, N-gram Language Models, and Hidden Markov Models (HMMs).
Core Characteristics:
Sparse Representations: Words are represented as high-dimensional, sparse vectors (e.g., one-hot vectors of size |V| where |V| is the vocabulary size).
No Semantic Continuity: The distance between "king" and "queen" is the same as between "king" and "apple".
Context-Blind: BoW ignores word order completely ("not good, very bad" and "good, not very bad" yield identical representations).
Deep NLP
Deep NLP represents text as continuous, dense vectors (word embeddings like Word2Vec, GloVe, or contextualized embeddings) and passes them through non-linear neural transformations.
Key Architectures: Recurrent Neural Networks (RNNs), LSTMs/GRUs, Convolutional Networks (1D-CNNs for text), and Transformers.
Core Characteristics:
Dense Representations: Features are compressed into fixed, low-dimensional dense vectors (e.g., d = 300, 512, 768).
Semantic Awareness: Captures complex relationships such as vector arithmetic: vec("King") - vec("Man") + vec("Woman") ≈ vec("Queen").
Sequential Context: Captures local and long-range dependencies across sequence positions.
Major Bottlenecks Comparison
| Dimension | Statistical NLP Bottlenecks | Deep NLP Bottlenecks |
|---|---|---|
| Sparsity & Scale | Out-of-Vocabulary (OOV) tokens cause failures; matrices become unmanageably large ( | V |
| Context | Fixed window size (N-grams); unable to capture dependencies beyond N-1 words. | Long-range context degradation in recurrent architectures (vanishing gradients). |
| Generalization | Fails to generalize to unseen phrases; strictly depends on exact matching frequencies. | Prone to overfitting on small datasets; requires massive volumes of pre-training data. |
2. Recurrent Neural Networks (RNNs) in NLP
Standard Feedforward Neural Networks (MLPs) assume all inputs are independent. Language, however, is sequential—the meaning of a word depends heavily on preceding context. Recurrent Neural Networks introduce an internal memory state (hidden state) to process sequence inputs.
At time step t, an RNN cell takes the current input vector x_t and the previous hidden state h_{t-1} to calculate the new hidden state h_t:
h_t = tanh(W_hh * h_{t-1} + W_xh * x_t + b_h)
ŷ_t = softmax(W_hy * h_t + b_y)
Where:
x_t: Input vector at step t
h_t: Hidden state vector acting as memory
W_hh, W_xh, W_hy: Trainable parameter weight matrices
b_h, b_y: Bias vectors
h_{t-1}
│
▼
x_t ──► [ RNN Cell ] ──► h_t
│
▼
ŷ_t
NLP Structural Variations
RNNs can be configured into distinct operational patterns depending on the input-to-output alignment:
One-to-One: Traditional feedforward classification (Single vector input → Single class label).
One-to-Many: Image Captioning (Single Image → Sequence of words).
Many-to-One: Sentiment Analysis or Text Classification (Sequence of words → Single sentiment label).
Many-to-Many (Synchronous): Named Entity Recognition (NER) or Part-of-Speech (POS) tagging (Sequence length T_in equals sequence length T_out). Each step emits an immediate output label.
Many-to-Many (Asynchronous / Seq2Seq): Machine Translation or Text Summarization (Sequence length T_in differs from sequence length T_out).
3. Seq2Seq Architecture (Encoder-Decoder)
When mapping an input sequence of length N to an output sequence of length M (where N ≠ M), direct frame-by-frame mapping fails. Cho et al. (2014) and Sutskever et al. (2014) introduced the Sequence-to-Sequence (Seq2Seq) Encoder-Decoder framework.
ENCODER DECODER
x_1 ──► [RNN] ──► h_1 y_1 ──► [RNN] ──► s_1 ──► Output 1
│ ▲
x_2 ──► [RNN] ──► h_2 │
│ Context Vector (c)
x_3 ──► [RNN] ──► h_3 ──► [Context Vector c] ───────────┘
1. The Encoder
The encoder is an RNN that reads input tokens x_1, x_2,..., x_T sequentially. At the final token x_T, the final hidden state h_T summarizes the entire input sequence:
$$c = h_T$$
This vector c is called the Context Vector (or bottleneck representation).
2. The Decoder
The decoder is another RNN trained to predict the next output token y_t given the context vector c and all previous generated tokens y_1,..., y_{t-1}:
$$s_t = f(s_{t-1}, y_{t-1}, c)$$
$$\hat{y}_t = \text{softmax}(W_s \cdot s_t)$$
Where s_t represents the hidden state of the decoder at step t.
4. Multi-Layer (Stacked) Deep RNNs
Single-layer RNNs struggle to learn complex hierarchical representations. Multi-Layer Deep RNNs stack recurrent layers on top of each other. The output hidden state of layer l-1 serves as the input sequence to layer l.
For layer l at step t:
$$h_t^{(l)} = \tanh\left(W_{hh}^{(l)} h_{t-1}^{(l)} + W_{xh}^{(l)} h_t^{(l-1)} + b^{(l)}\right)$$
Layer 2 ──► [RNN] ──► [RNN] ──► [RNN]
▲ ▲ ▲
Layer 1 ──► [RNN] ──► [RNN] ──► [RNN]
▲ ▲ ▲
Inputs ──► x_1 x_2 x_3
Depth Advantages & Costs
Advantage: Layer 1 captures low-level features (syntax, local n-grams), while deeper layers capture high-level semantic abstractions.
Cost: Training deep RNNs dramatically amplifies numerical stability challenges during Backpropagation Through Time (BPTT).
5. Critical Issues with Vanilla RNNs
Despite their initial success, vanilla RNNs suffer from fundamental algorithmic flaws:
1. Vanishing and Exploding Gradients
During BPTT over T time steps, the gradient of the loss L with respect to state h_1 contains repeated matrix multiplications of the weight matrix transpose (W_hh)^T.
Vanishing Gradients: If the eigenvalues of W_hh are smaller than 1, gradients decay exponentially toward 0 as sequence length T increases. The model forgets early inputs.
Exploding Gradients: If the eigenvalues of W_hh exceed 1, gradients grow exponentially, causing numerical overflow (
NaN).
(Note: Gates in LSTMs/GRUs mitigate vanishing gradients partially, but do not solve the structural computational bottleneck).
2. Information Bottleneck Problem
In traditional Seq2Seq models, the entire input sentence—whether 5 words or 100 words—must be compressed into a single, fixed-size vector c. This creates severe memory degradation on longer sequences.
3. Sequential Processing Constraint (Non-Parallelizability)
Computing h_t strictly requires h_{t-1}. This sequential dependency makes it impossible to parallelize training across tokens within a sequence on modern GPU architectures, severely limiting throughput on large datasets.
6. Seq2Seq RNN with Attention
To solve the fixed-vector bottleneck, Bahdanau et al. (2014) introduced the Attention Mechanism. Instead of relying on a single static context vector c, the decoder creates a dynamic context vector c_i for every single output step i by taking a weighted sum of all encoder hidden states.
Encoder States: h_1 h_2 h_3
│ │ │
└───┬───┴───┬───┘
▼ ▼
[ Attention Alignment ] ──► Weights (α_i1, α_i2, α_i3)
│
▼
Context Vector (c_i) ──► Decoder State (s_i)
Mathematical Steps (Bahdanau Attention)
- Alignment Scores: Score how well the encoder state h_j matches the previous decoder state s_{i-1}:
$$e_{ij} = v_a^T \tanh(W_a s_{i-1} + U_a h_j)$$
- Attention Weights: Normalize alignment scores across all encoder positions using Softmax:
$$\alpha_{ij} = \frac{\exp(e_{ij})}{\sum_{k=1}^{T_{in}} \exp(e_{ik})}$$
- Dynamic Context Vector Construction: Compute the weighted sum of encoder states:
$$c_i = \sum_{j=1}^{T_{in}} \alpha_{ij} h_j$$
- Decoder Update: Combine c_i with the current state to produce output y_i.
7. The Attention Layer: Query, Key, and Value (Q, K, V)
Vaswani et al. (2017) generalized attention into a query-retrieval operation using Query (Q), Key (K), and Value (V) matrices, abstracting attention away from recurrent architectures.
Conceptual Analogy
Think of Attention as a database lookup:
Query (Q): What you are searching for.
Key (K): The labels/tags of the stored records.
Value (V): The actual underlying content of the records.
Instead of retrieving a single item (hard lookup), attention performs a soft, probabilistic lookup, returning a weighted mixture of all Values based on the similarity between the Query and each Key.
Matrix Projections
Given an input matrix X in R^(N × d_model) (where N is sequence length and d_model is embedding dimension), we project X using learned parameter matrices:
$$Q = X W^Q \quad \text{where } W^Q \in \mathbb{R}^{d_{\text{model}} \times d_k}$$
$$K = X W^K \quad \text{where } W^K \in \mathbb{R}^{d_{\text{model}} \times d_k}$$
$$V = X W^V \quad \text{where } W^V \in \mathbb{R}^{d_{\text{model}} \times d_v}$$
Scaled Dot-Product Attention Equation
$$\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{Q K^T}{\sqrt{d_k}}\right) V$$
Step-by-Step Breakdown:
Dot Product Similarity (Q Kᵀ): Computes pairwise dot-products between all queries and keys.
- Shape: (N × d_k) × (d_k × N) = (N × N)
Scaling Factor (√(d_k): Divides similarity scores by √(d_k).
- Why? For large values of d_k, the magnitude of the dot products grows large, pushing the Softmax function into regions with extremely small gradients. Scaling keeps variance at 1.
Softmax Normalization: Converts continuous dot-product scores into valid probability distributions along rows:
$$A_{ij} = \frac{\exp\left(\frac{Q_i K_j^T}{\sqrt{d_k}}\right)}{\sum_{k} \exp\left(\frac{Q_i K_k^T}{\sqrt{d_k}}\right)}$$
Weighted Value Sum (A V): Multiplies attention weights by Value matrix V.
- Shape: (N × N) × (N × d_v) = (N × d_v)
8. Variants of Attention Mechanisms
Depending on how Queries, Keys, and Values are derived and constrained, Attention manifests in four core configurations:
1. Self-Attention
What it is: Queries, Keys, and Values are derived from the same input sequence (Q = XW^Q, K = XW^K, V = XW^V).
Why use it: Allows tokens within a single sentence to interact with every other token in that same sentence.
When to use: Sentence encoding, context modeling (e.g., BERT, Encoder blocks).
2. Cross-Attention (Encoder-Decoder Attention)
What it is: Queries (Q) come from the target sequence (Decoder hidden states), while Keys (K) and Values (V) come from the source sequence (Encoder output states).
Why use it: Connects target generation steps directly to relevant parts of the source text.
When to use: Sequence-to-sequence translation, summarize-from-source setups, multi-modal tasks (e.g., Text-to-Image generation).
3. Multi-Head Attention (MHA)
- What it is: Instead of computing attention once with d_model dimensions, we project Q, K, V into h different subspaces of dimension d_k = d_model / h and perform scaled dot-product attention concurrently across all h heads.
$$\text{head}_i = \text{Attention}(Q W_i^Q, K W_i^K, V W_i^V)$$
$$\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \text{head}_2, \dots, \text{head}_h) W^O$$
Why use it: A single attention head tends to average out dependencies. Multi-Head Attention allows the model to jointly attend to information from different representation subspaces at different positions.
When to use: Standard component across modern Transformer architectures (e.g., GPT, BERT, T5).
4. Masked Attention (Causal Attention)
- What it is: Self-attention where attention scores for future positions are set to -∞ prior to applying Softmax:
$$\text{MaskedAttention}(Q,K,V) = \text{softmax}\left(\frac{Q K^T + M}{\sqrt{d_k}}\right) V$$
$$\text{where } M_{ij} = \begin{cases} 0 & \text{if } i \geq j \ -\infty & \text{if } i < j \end{cases}$$
Why use it: Ensures causality during autoregressive generation. Prevents position i from attending to future positions i+1, i+2, ..., N.
When to use: Autoregressive language modeling (e.g., GPT-3, GPT-4, Llama).
9. NLP Tasks Mapped to Attention Patterns
Different NLP task structures dictate how attention inputs and masking are configured:
1. Many-to-One Tasks (Classification / Sentiment Analysis)
Architecture Setup: Self-Attention without Causal Masking.
Pattern: Every token attends to every other token bidirectionally.
Aggregation: The model aggregates sequence-wide contextual information into a specialized pooling token (e.g.,
[CLS]) or via mean-pooling across the sequence dimension.Classification Head: The final pooled vector is passed through a Linear + Softmax layer to emit a class probability distribution.
Input Tokens ──► [ Unmasked Self-Attention ] ──► [ Mean / CLS Pooling ] ──► [ Linear Classifier ] ──► Label
2. One-to-Many / Autoregressive Many-to-Many Tasks (Generation / Translation)
Architecture Setup: Causal Masked Self-Attention + Cross Attention.
Pattern:
In auto-regressive decoding, output step t queries previous steps 1,2,...,t-1 via Causal Masking.
In cross-attention, decoder step t queries all 1,2,..., N encoder keys/values simultaneously.
Generation Head: At each decoder step, the output state passes through a linear layer of vocabulary size |V| to sample the next predicted token.
Past Outputs ──► [ Masked Self-Attention ] ──┐
├──► [ Linear Layer ] ──► Next Token
Encoder Out ──► [ Cross-Attention ] ───────┘
Summary Roadmap
Statistical NLP: High-dimensional sparse counts → limited by context and out-of-vocabulary terms.
RNNs: Introduced stateful hidden memory → limited by vanishing gradients and sequential computational bottlenecks.
Seq2Seq: Split processing into Encoder and Decoder → created information compression bottlenecks.
Attention Mechanisms: Introduced dynamic Q, K, V matrix operations → enabled parallel processing, preserved long-range context, and became the foundation of modern deep learning for text.
Comments
Join the discussionNo comments yet. Be the first to comment.