Classical to Modern NLP: Text Processing, Embeddings, Transformers, and LLMs
Primary references:
- Anthropic: Introducing Contextual Retrieval
- Stanford CS: Embeddings
- Sebastian Raschka: Building Reasoning Models
Overview
Natural Language Processing, or NLP, has evolved from rule-based text processing and sparse lexical representations to dense embeddings, Transformers, and large language models.
This document follows that progression:
- Classical text processing: tokenization, normalization, Bag of Words, TF-IDF, and BM25.
- Representation learning: Word2Vec, FastText, Poincare embeddings, and semantic search.
- Sequence modeling: RNNs, LSTMs, Seq2Seq, and Transformers.
- Modern LLMs: pretraining, fine-tuning, retrieval-augmented generation, and reasoning models.
Part 1: Classical Text Processing
Module 1: Text Normalization
Text pipeline
Raw text
|
v
Lowercasing / Unicode normalization
|
v
Sentence segmentation
|
v
Tokenization
|
v
Stop-word removal
|
v
Stemming or lemmatization
|
v
Vector representation
Normalization
Normalization makes text more consistent before modeling.
Common operations include:
- Lowercasing.
- Removing punctuation.
- Expanding contractions.
- Unicode normalization.
- Removing or retaining numbers.
- Removing stop words.
- Handling whitespace.
Normalization choices are task-dependent. For sentiment analysis, punctuation and emojis may carry meaning. For BM25 retrieval, preserving exact identifiers such as TS-999 may be essential. anthropic
Module 2: Tokenization
Tokenization breaks text into units that a model can process.
| Token type | Example | Use case |
|---|---|---|
| Character | m, o, d, e, l | Robust to rare words, longer sequences |
| Word | machine, learning | Simple, but poor for unknown words |
| Subword | mach, ine, learning | Balances vocabulary size and coverage |
| Byte-level | UTF-8 bytes | Language-agnostic, handles arbitrary text |
Byte-Pair Encoding
Byte-Pair Encoding, or BPE, starts with characters and iteratively merges the most frequent adjacent pairs.
Corpus:
low lower lowest
Initial tokens:
l o w
l o w e r
l o w e s t
Frequent merge:
lo
Later merges:
low
low + er
low + est
BPE is used in GPT-style models.
WordPiece
WordPiece is used in BERT. It represents continuation pieces with a ## marker.
unaffable
= un ##aff ##able
SentencePiece
SentencePiece treats text as a raw Unicode stream and can operate directly without pre-tokenization. It is used in models such as T5 and XLNet.
Tokenization trade-offs
| Choice | Benefit | Cost |
|---|---|---|
| Word-level tokens | Human-readable, simple | Large vocabulary, poor OOV handling |
| Subword tokens | Handles rare and unknown words | Less directly interpretable |
| Character tokens | No OOV problem | Longer sequences |
| Byte-level tokens | Universal coverage | More tokens per word |
Module 3: Stemming and Lemmatization
| Method | Approach | Example | Strength | Limitation |
|---|---|---|---|---|
| Stemming | Rule-based truncation | running to run | Fast | Can produce invalid stems |
| Lemmatization | Dictionary and POS-aware normalization | better to good | Linguistically accurate | Slower and more complex |
Stemming removes affixes using rules. Lemmatization maps a word form to its dictionary base form, or lemma.
For example, mice maps to the lemma mouse, and sang maps to the lemma sing. A lemma can have multiple senses; this property is called polysemy. vllm-sr
Part 2: Classical Vector Representations
Module 4: Bag of Words
Bag of Words, or BoW, represents a document as a vector of word counts.
Documents:
D1: "machine learning is useful"
D2: "deep learning is powerful"
Vocabulary:
[machine, learning, is, useful, deep, powerful]
D1 vector:
[1, 1, 1, 1, 0, 0]
D2 vector:
[0, 1, 1, 0, 1, 1]
BoW ignores word order and grammar. The sentences “dog bites man” and “man bites dog” receive identical representations.
Module 5: TF-IDF
TF-IDF weights a term by how frequent it is in a document and how rare it is across the corpus.
\[\text{tf-idf}(i,j) = \text{tf}(i,j) \cdot \text{idf}(i)\]where:
\[\text{idf}(i) = \log\left(\frac{N}{\text{df}_i}\right)\]and:
- $\text{tf}(i,j)$ is the frequency of term $i$ in document $j$.
- $N$ is the total number of documents.
- $\text{df}_i$ is the number of documents containing term $i$.
A term that appears in many documents receives a lower IDF weight. A term that is frequent in one document but rare across the corpus receives a high TF-IDF score.
Module 6: BM25 Retrieval
Okapi BM25 is a lexical ranking function built on TF-IDF. It adds term-frequency saturation and document-length normalization. anthropic
\[\text{Score}(D,Q) = \sum_{i=1}^{n} \text{IDF}(q_i) \cdot \frac{ f(q_i,D)(k_1+1) }{ f(q_i,D) + k_1 \left( 1-b + b\frac{|D|}{\text{avgdl}} \right) }\]where:
- $D$ is a document.
- $Q$ is a query.
- $q_i$ is a query term.
- $f(q_i,D)$ is the frequency of term $q_i$ in document $D$.
-
$ D $ is the document length. - $\text{avgdl}$ is the average document length.
- $k_1$ controls term-frequency saturation.
- $b$ controls document-length normalization.
Why BM25 matters
BM25 is particularly effective for exact identifiers, technical terms, product codes, and error strings. For example, Anthropic notes that an embedding model may retrieve content about error codes in general, while BM25 can find the exact string Error code TS-999. anthropic
Query: "Error code TS-999"
Embedding retrieval:
May return documents about error codes generally.
BM25 retrieval:
Finds documents containing the exact string "TS-999".
BM25 versus embeddings
| Property | BM25 | Dense embeddings |
|---|---|---|
| Matching style | Exact lexical matching | Semantic similarity |
| Handles synonyms | Weak | Strong |
| Handles identifiers | Strong | Can miss exact strings |
| Interpretability | High | Lower |
| Typical representation | Sparse term weights | Dense vector |
Hybrid retrieval combines both approaches. anthropic
Part 3: Embeddings and Semantic Search
Module 7: Distributional Hypothesis
The distributional hypothesis states that words occurring in similar contexts tend to have similar meanings. Vector semantics represents word meaning as a point in a multidimensional space derived from word distributions. vllm-sr
Word contexts
|
v
Co-occurrence statistics
|
v
Vector representation
|
v
Semantic similarity
For example, if ongchoi appears near words such as garlic, rice, delicious, and salty, and words such as spinach, chard, and collard greens appear in similar contexts, then ongchoi is likely a leafy green. vllm-sr
Module 8: Count-Based Embeddings
A word-context matrix records how often words co-occur within a context window.
Context window: +/- 4 words
Corpus:
... traditionally followed by cherry pie ...
Target word: cherry
Context words: traditionally, followed, by, pie
Each row of the matrix is a vector representing a word. In a full vocabulary-sized matrix, vectors are extremely sparse because most words never co-occur with most other words. vllm-sr
| Representation | Dimension | Density | Example |
|---|---|---|---|
| Count vector | Vocabulary size, often 10,000 to 50,000 | Sparse | [0, 2, 8, 9, 442, 25] |
| TF-IDF vector | Vocabulary size | Sparse | Weighted term frequencies |
| Dense embedding | 50 to 1,000 | Dense | Real-valued learned vector |
Sparse vectors can work well, but dense embeddings usually perform better because they require fewer learned parameters and can capture similarity between related but distinct words. vllm-sr
Module 9: Cosine Similarity
Cosine similarity measures the angle between two vectors:
\[\text{cosine}(v,w) = \frac{v \cdot w} {\|v\|\|w\|} = \frac{ \sum_{i=1}^{N} v_i w_i }{ \sqrt{\sum_{i=1}^{N} v_i^2} \sqrt{\sum_{i=1}^{N} w_i^2} }\]where:
- $v$ and $w$ are vectors.
- $v \cdot w$ is the dot product.
- $|v|$ and $|w|$ are vector lengths.
Cosine similarity is preferred over raw dot product because raw dot product favors longer vectors, which are often associated with more frequent words. Cosine normalizes for vector length. vllm-sr
For non-negative frequency vectors, cosine similarity ranges from 0 to 1. For real-valued embeddings, it ranges from -1 to 1. vllm-sr
Similar vectors:
Small angle -> cosine close to 1
Orthogonal vectors:
90-degree angle -> cosine 0
Opposite vectors:
180-degree angle -> cosine -1
Module 10: Word2Vec
Word2Vec learns dense vector representations using shallow neural networks.
| Variant | Prediction task |
|---|---|
| Skip-gram | Predict context words from a target word |
| CBOW | Predict a target word from averaged context words |
Skip-gram with negative sampling
Skip-gram with Negative Sampling, or SGNS, trains a binary classifier to distinguish a true context word from randomly sampled noise words. vllm-sr
Sentence:
... lemon, a tablespoon of apricot jam, a pinch ...
Target word: apricot
Context window: +/- 2 words
Positive examples:
apricot -> tablespoon
apricot -> of
apricot -> jam
apricot -> a
Negative examples:
apricot -> aardvark
apricot -> seven
The model computes:
\[P(+ \mid w,c) = \sigma(c \cdot w) = \frac{1} {1 + e^{-c \cdot w}}\]where:
- $w$ is the target-word embedding.
- $c$ is the candidate-context embedding.
- $\sigma$ is the sigmoid function.
The loss is:
\[\mathcal{L}_{NS} = -\log \sigma(v'_{w_O}{}^\top v_{w_I}) - \sum_{i=1}^{k} \log \sigma(-v'_{n_i}{}^\top v_{w_I})\]where:
- $v_{w_I}$ is the input-word embedding.
- $v’_{w_O}$ is the output embedding for the true context word.
- $v’_{n_i}$ is the output embedding for negative sample $n_i$.
- $k$ is the number of negative samples.
SGNS commonly samples negative words using a smoothed unigram distribution:
\[P_{\alpha}(w) = \frac{ \text{count}(w)^{\alpha} }{ \sum_{w'} \text{count}(w')^{\alpha} }\]where $\alpha$ is commonly set to 0.75. This gives rare words a slightly higher sampling probability than their raw frequency would imply. vllm-sr
Static embeddings
Word2Vec produces static embeddings: one fixed vector per vocabulary word. In contrast, contextualized models such as BERT produce different vectors for the same word in different contexts. vllm-sr
Module 11: FastText and Poincare Embeddings
FastText
FastText incorporates subword character n-grams. This makes it more robust for out-of-vocabulary words and morphologically rich languages.
Word: "learning"
Subword units:
<le
lea
ear
arn
rni
nin
ing
ng>
Poincare embeddings
Poincare embeddings use hyperbolic geometry, specifically the Poincare ball model, to embed hierarchical graph structures and taxonomies with low distortion.
Root
|
+--> Animal
| |
| +--> Dog
| +--> Cat
|
+--> Vehicle
|
+--> Car
+--> Bicycle
Hyperbolic space can represent tree-like structures more efficiently than Euclidean space.
Part 4: Sequence Models
Module 12: Recurrent Neural Networks
Recurrent Neural Networks, or RNNs, process sequences one token at a time while maintaining a hidden state.
x1 --> [RNN cell] --> h1
|
v
x2 --> [RNN cell] --> h2
|
v
x3 --> [RNN cell] --> h3
where:
- $x_t$ is the input token at time $t$.
- $h_t$ is the hidden state at time $t$.
RNNs can model order, but they struggle with long-range dependencies because gradients can vanish or explode during backpropagation through time.
Module 13: LSTM and GRU
Long Short-Term Memory networks, or LSTMs, mitigate vanishing gradients using gates and a dedicated cell state.
| Component | Role |
|---|---|
| Forget gate | Decides what to discard from cell state |
| Input gate | Decides what new information to store |
| Output gate | Decides what to expose as hidden state |
| Cell state | Long-term memory pathway |
Input token
|
v
Recurrent cell
|
+--> Hidden state
|
+--> Cell state
|
v
Next token
Gated Recurrent Units, or GRUs, use a simpler gating structure with update and reset gates.
Module 14: Seq2Seq Models
Sequence-to-sequence models map variable-length input sequences to variable-length output sequences.
Input sequence
|
v
Encoder RNN
|
v
Context vector
|
v
Decoder RNN
|
v
Output sequence
Training commonly uses teacher forcing: the decoder receives the true previous token rather than its own prediction.
Inference commonly uses beam search, which maintains multiple high-probability output hypotheses.
Limitations
- The context vector can become a bottleneck for long inputs.
- Recurrence prevents full parallelization.
- Long-range dependencies remain difficult.
- Attention was introduced to address these weaknesses.
Part 5: Transformers
Module 15: Transformer Architecture
The Transformer replaces recurrence with attention, enabling massive parallelization.
Input tokens
|
v
Token embeddings
|
v
Positional encoding
|
v
Multi-head self-attention
|
v
Feed-forward network
|
v
Layer normalization and residuals
|
v
Output representations
Module 16: Attention
Scaled dot-product attention
\[\text{Attention}(Q,K,V) = \text{softmax} \left( \frac{QK^T}{\sqrt{d_k}} \right)V\]where:
- $Q$ is the query matrix.
- $K$ is the key matrix.
- $V$ is the value matrix.
- $d_k$ is the key dimension.
- $QK^T$ computes similarity between queries and keys.
- $\sqrt{d_k}$ prevents excessively large dot products.
Multi-head attention
Multi-head attention projects queries, keys, and values into multiple subspaces. Each head can attend to different relationships simultaneously.
Input representation
|
+--> Head 1
|
+--> Head 2
|
+--> Head 3
|
v
Concatenate heads
|
v
Output projection
Module 17: Positional Encoding
Self-attention is permutation-invariant: it does not inherently know token order. Positional encodings inject order information.
Sinusoidal positional encodings use functions of varying frequency:
\[PE_{(pos,2i)} = \sin \left( \frac{pos}{10000^{2i/d}} \right)\] \[PE_{(pos,2i+1)} = \cos \left( \frac{pos}{10000^{2i/d}} \right)\]where:
- $pos$ is the token position.
- $i$ is the dimension index.
- $d$ is the embedding dimension.
Module 18: Layer Normalization
Layer normalization stabilizes activations within each layer.
Post-LN Transformers apply normalization after a residual block. Pre-LN Transformers place normalization inside the residual block, before the sub-layer.
Pre-LN supports stable gradient flow at initialization and reduces dependence on learning-rate warm-up.
Part 6: Modern LLMs
Module 19: Pretraining Paradigms
| Family | Examples | Training objective | Best for |
|---|---|---|---|
| Encoder-only | BERT, RoBERTa | Masked Language Modeling | Classification, extraction, understanding |
| Decoder-only | GPT family | Causal next-token prediction | Generation, chat, agents |
| Encoder-decoder | T5, BART | Denoising or seq2seq objectives | Translation, summarization, structured generation |
BERT is pretrained with Masked Language Modeling, or MLM, and Next Sentence Prediction, or NSP.
GPT models are decoder-only autoregressive models trained with causal next-token prediction.
Module 20: Fine-Tuning
Full fine-tuning
Full fine-tuning updates all model parameters. It can achieve strong task performance but requires substantial memory and compute.
LoRA
Low-Rank Adaptation, or LoRA, freezes pretrained weights $W_0$ and injects trainable low-rank matrices:
\[\Delta W = BA\] \[h = W_0x + \Delta Wx = W_0x + BAx\]where:
- $W_0$ is the frozen pretrained weight matrix.
- $B$ and $A$ are trainable low-rank matrices.
- $x$ is the input representation.
QLoRA
QLoRA combines:
- 4-bit NormalFloat quantization.
- Double quantization.
- Paged optimizers.
This enables fine-tuning large LLMs on consumer-grade hardware.
Module 21: Alignment
RLHF
Reinforcement Learning from Human Feedback, or RLHF, aligns models using a learned reward model and Proximal Policy Optimization, or PPO.
Prompt
|
v
Policy model generates responses
|
v
Reward model scores responses
|
v
PPO updates policy
DPO
Direct Preference Optimization, or DPO, directly optimizes the policy model from preference pairs without explicitly training and sampling from a separate reward model.
Prompt
|
+--> Chosen response
|
+--> Rejected response
|
v
Preference optimization
Module 22: Reasoning Models
A reasoning model is an LLM enhanced through additional post-training, often using reinforcement learning with verifiable rewards, and optionally inference-time scaling techniques.
User task
|
v
Reasoning model
|
+--> Generate reasoning trace
|
+--> Produce final answer
|
v
Verifier or reward model
Reasoning models are commonly developed for math and code, but their capabilities can generalize to other problem domains.
Inference-time scaling
Inference-time scaling improves answers while keeping model weights fixed.
| Technique | Mechanism |
|---|---|
| Temperature sampling | Samples diverse completions |
| Top-p filtering | Restricts sampling to high-probability tokens |
| Self-consistency | Uses majority voting over multiple answers |
| Self-refinement | Critiques and revises an answer |
| Best-of-N | Selects the best candidate using a scorer |
These techniques trade additional inference compute for potentially higher accuracy.
RLVR and GRPO
Reinforcement Learning with Verifiable Rewards, or RLVR, uses a verifier to provide a reward signal. For math, a verifier can check whether an extracted final answer is mathematically equivalent to the reference answer.
Group Relative Policy Optimization, or GRPO, generates groups of responses, scores them with a verifier, and uses relative rewards within each group for policy updates.
Prompt
|
v
Generate group of responses
|
v
Verifier scores each response
|
v
Compute relative advantages
|
v
Update policy
Distillation
Distillation trains a smaller student model using outputs from a stronger teacher model.
| Type | Mechanism |
|---|---|
| Hard distillation | Train on teacher-generated text labels |
| Soft distillation | Train on teacher probability distributions |
| On-policy distillation | Student generates samples, teacher provides feedback |
| Off-policy distillation | Train on teacher-generated examples |
Distillation is an alternative to reinforcement learning for building reasoning capability.
Part 7: Retrieval-Augmented Generation
Module 23: RAG Pipeline
Retrieval-Augmented Generation, or RAG, retrieves relevant external knowledge and appends it to the model prompt.
User query
|
v
Dense retrieval + sparse retrieval
|
v
Rank fusion and deduplication
|
v
Top-K chunks
|
v
LLM generation
Standard RAG preprocessing involves: anthropic
- Splitting a corpus into chunks, usually no more than a few hundred tokens.
- Creating embedding vectors for chunks.
- Storing embeddings in a vector database.
- Retrieving semantically similar chunks at query time.
- Adding retrieved chunks to the prompt.
Module 24: Hybrid Retrieval
Hybrid retrieval combines dense semantic retrieval with sparse lexical retrieval.
User query
|
+--> Contextual embeddings --> semantic candidates
|
+--> Contextual BM25 ------> lexical candidates
|
v
Rank fusion and deduplication
|
v
Top-K chunks
|
v
LLM generation
Embeddings capture semantic relationships. BM25 captures exact lexical matches, which is valuable for identifiers, titles, SKUs, artist names, and error codes. anthropic
Module 25: Contextual Retrieval
Traditional RAG can destroy context during chunking. For example, the sentence:
The company's revenue grew by 3% over the previous quarter.
does not identify the company or time period. Contextual Retrieval prepends chunk-specific explanatory context before embedding and BM25 indexing. anthropic
Original chunk:
"The company's revenue grew by 3% over the previous quarter."
Contextualized chunk:
"This chunk is from an SEC filing on ACME corp's performance in Q2 2023;
the previous quarter's revenue was $314 million.
The company's revenue grew by 3% over the previous quarter."
Anthropic reports:
| Configuration | Top-20 retrieval failure rate | Reduction |
|---|---|---|
| Standard retrieval baseline | 5.7% | — |
| Contextual Embeddings | 3.7% | 35% |
| Contextual Embeddings plus Contextual BM25 | 2.9% | 49% |
| Plus reranking | 1.9% | 67% |
The generated contextual text is usually 50 to 100 tokens and is prepended to each chunk before embedding and BM25 indexing. anthropic
Module 26: Reranking
Reranking filters an initial retrieval set before generation.
Initial retrieval: top 150 chunks
|
v
Reranking model scores chunks
|
v
Select top 20 chunks
|
v
LLM generation
Anthropic used the Cohere reranker in its experiments and found that reranked Contextual Embedding plus Contextual BM25 reduced top-20 retrieval failure by 67%, from 5.7% to 1.9%. anthropic
Reranking improves relevance but adds runtime latency and cost. There is a trade-off between reranking more chunks for better performance and reranking fewer chunks for lower latency and cost. anthropic
Module 27: Vector Indexes
Approximate Nearest Neighbor, or ANN, search uses structures such as:
| Index | Mechanism | Strength |
|---|---|---|
| HNSW | Hierarchical navigable small-world graph | Fast approximate graph search |
| Product Quantization, PQ | Compresses vectors into codebooks | Lower memory footprint |
| IVF | Inverted file partitions | Efficient candidate pruning |
These indexes trade exact recall for lower latency and memory use.
Part 8: Limitations and Open Questions
Classical NLP limitations
- BoW ignores word order and grammar.
- TF-IDF and BM25 do not understand paraphrases or semantics.
- Stemming can produce invalid word forms.
- Word-level tokenization struggles with out-of-vocabulary words.
- Count-based vectors are high-dimensional and sparse.
Embedding limitations
- Static embeddings assign one vector per word despite context-dependent meaning.
- Dense embeddings are less directly interpretable than lexical features.
- Embedding similarity does not imply factual correctness or causality.
- Embedding models can miss exact identifiers and rare technical strings. anthropic
Transformer and LLM limitations
- Attention cost grows with sequence length.
- Long contexts increase memory and latency.
- LLMs can hallucinate unsupported facts.
- Fine-tuning can cause catastrophic forgetting.
- Reasoning traces can be long, expensive, and difficult to evaluate.
RAG limitations
- Poor chunk boundaries can harm retrieval.
- Context generation adds preprocessing cost.
- Reranking adds runtime latency.
- More retrieved chunks can distract the generator.
- Retrieval metrics and generation metrics should be evaluated separately.
Anthropic found that passing 20 chunks was more effective than 5 or 10 in its experiments, but recommends experimenting per use case because additional context can also distract the model. anthropic
Final Technical Takeaways
- Central mechanism: NLP progresses from text normalization and lexical matching to dense representations, attention-based sequence modeling, and LLM generation.
- Main classical insight: TF-IDF and BM25 remain powerful because they capture exact lexical evidence that semantic embeddings can miss. anthropic
- Main representation insight: The distributional hypothesis motivates embeddings: words with similar contexts receive similar vectors. vllm-sr
- Main similarity insight: Cosine similarity compares direction rather than magnitude, making it the standard similarity measure for sparse and dense embeddings. vllm-sr
- Main transformer insight: Self-attention replaces recurrence with parallelizable token interactions, while positional encodings restore order information.
- Main LLM insight: Pretraining teaches general language ability; fine-tuning, alignment, and retrieval adapt it to domains, preferences, and private knowledge.
- Main retrieval insight: Hybrid retrieval plus contextual chunking plus reranking can substantially improve retrieval accuracy. anthropic
- Main reasoning insight: Reasoning capability can be improved through verifiable-reward reinforcement learning, inference-time scaling, or distillation.
- Main trade-off: More context, more reasoning, and more retrieval improve quality but increase latency, cost, and complexity.
- Broader engineering implication: Build NLP systems as measurement-driven pipelines: choose the right representation, retrieve grounded evidence, evaluate retrieval and generation separately, and optimize for both quality and cost. anthropic