Static vs Contextual Embeddings
Understand the fundamental limitation of static embeddings and why contextual representations require attention. This is the conceptual bridge from vectors to transformers — where the meaning of "the bank" depends entirely on whether you're fishing or depositing.
Static vs Contextual: The Raw Clay vs The Sculpted Figure
A static embedding (Word2Vec) is a block of raw uncarved clay pulled from the scholar's shelf for "bank"—it cannot distinguish a financial vault from a muddy river shore. A contextual embedding (Transformers) happens when the scholar's self-attention mechanism lets "bank" converse with surrounding tokens ("river", "water", "mud"), dynamically sculpting and bending the vector into an aquatic riverbank representation!
IntroductionTwo kinds of embeddings
Every token in a language model starts its life as a static vector — a row pulled from an embedding table by token ID. But this single fixed vector cannot capture the fact that language is deeply contextual. Two kinds of embeddings exist, and understanding the difference is essential to understanding why transformers work the way they do.
Static embeddings
One fixed vector per vocabulary token, regardless of context. Word2Vec gives "bank" the same 300-dimensional vector in every sentence it appears in — forever.
Contextual embeddings
The representation of a token changes based on surrounding tokens. BERT gives "bank" a different hidden-state vector in "river bank" vs "bank account".
- Static = same number regardless of which sentence the token appears in.
- Contextual = the representation of a token depends on its neighbours — computed by attention layers, not just table lookup.
WhyThe polysemy problem
Natural language is full of polysemous words — single words with multiple distinct meanings. A static embedding can only encode one vector per token, so it inevitably averages over all the word's meanings. This averaging loses critical information.
"bank"
River bank (geography) vs bank account (finance). Completely different concepts, one token, one static vector.
"bat"
Cricket bat (sport equipment) vs a bat (nocturnal animal). The word is identical; the meaning is not.
"light"
Light the candle (verb: ignite) vs the bag is light (adjective: not heavy) vs the light is bright (noun: illumination).
"lead"
Lead the team (verb: guide) vs lead pipe (noun: metal) vs lead guitar (adjective: primary).
IntuitionThe frozen photo vs the live camera
The clearest analogy: a static embedding is like a passport photo. No matter what you are doing today — whether you are at a beach, in a courtroom, or running a marathon — your passport always shows the same picture. The photo does not change based on context.
A contextual embedding is like a live camera feed. Your appearance (representation) shifts based on what surrounds you — who else is in the frame, what activity is happening, what environment you're in. The system sees you in context.
Passport photo (static)
Taken once. Fixed forever. Sent to every country that needs to identify you. Does not capture that today you might be in a totally different context.
Live camera (contextual)
Continuously updated. Captures the scene. Your appearance is shaped by the surrounding context — costume, lighting, companions — at every moment.
Theory: StaticWord2Vec, GloVe, FastText
Static embedding methods train by predicting word co-occurrences over a large corpus. The result is a fixed lookup table: one vector per vocabulary item, trained once, used at inference without modification.
| Method | Training objective | Key insight | Limitation |
|---|---|---|---|
| Word2Vec | Skip-gram: predict neighbours from a centre word; or CBOW: predict centre from neighbours. Explicit context window (typically 5 tokens). | Words that appear in similar contexts get similar vectors — distributional hypothesis. | One vector per word form. "bank" in finance and "bank" in geography share one vector. |
| GloVe | Factorises the global word–word co-occurrence matrix. Balances local and global statistics. | Captures analogy structure more reliably (king − man + woman ≈ queen). | Still one vector per word. No sentence-level context. Large matrix is expensive to build. |
| FastText | Extends Word2Vec with subword n-gram representations. Each word vector is the sum of its character n-gram vectors. | Can handle out-of-vocabulary words by composing character n-grams. Better for morphologically rich languages. | Still static — the vector for a word is fixed regardless of sentence context. |
bank → same [0.12, −0.41, 0.77, …] regardless of whether it follows "river" or "savings". The vector does not adapt.
Strengths of static embeddings: fast to compute at inference time (pure table lookup), small memory footprint, good baseline for general word similarity tasks, easy to inspect and visualise.
Theory: ContextualBERT, GPT, and modern transformers
Modern transformer models (BERT, GPT, T5, LLaMA) produce contextual representations. The initial token embedding is still static — it comes from the same kind of embedding table — but attention layers transform it based on surrounding tokens. The final hidden state for a token is contextual.
This is precisely why the Attention mechanism exists — it is the engine that converts static embeddings into contextual representations by allowing each token to look at its neighbours and update accordingly.
How It WorksFrom token to contextual representation
The full pipeline from raw text to contextual hidden state, step by step:
- Tokenize: Split raw text into tokens (WordPiece, BPE, SentencePiece…).
- Token ID lookup: Convert tokens to integer IDs using the vocabulary.
- Embedding table lookup: Each ID indexes one row in the embedding matrix $E \in \mathbb{R}^{V \times d}$. This is the static embedding.
- Positional encoding: Add position information — transformer has no inherent notion of order.
- Attention layers: Each layer computes attention scores between all token pairs, allowing each token's representation to be updated based on context.
- Output: Final hidden states — one $d$-dimensional vector per token, fully contextual. These are what downstream tasks use.
Worked Example"bank" in two sentences
Consider the word "bank" in two sentences with completely different meanings. We trace what happens at each layer.
[0.12, −0.41, 0.77, …] (same row in embedding table). No difference yet.
Sentence 2: "bank" has now attended to "river" (strong geographic signal) → representation shifts toward geographic domain.
Sentence 2: $h_{\text{bank}}^{\text{geo}} \approx [−0.28, 0.71, 0.45, …]$ — geographic context vector.
These two vectors are measurably different. Cosine similarity between them is significantly below 1.0 for a trained model.
VisualizeSame start, diverging paths
The Mermaid diagram below shows how both sentences start from the identical static embedding for "bank" but end up with different contextual representations after the attention layers operate.
The dashed lines show the key contrast: the static embeddings are identical (same starting point), while the final hidden states are different (context has differentiated them). This is the mechanism attention provides — and the reason contextual representations require it.
🔍 Behind-the-Scenes: The Layer-by-Layer Attention Transformation
How a 12-layer Transformer separates identical word tokens:
- Layer 0 (Static Input): Both sentences retrieve identical static vector $\vec{e}_{\text{bank}} = \mathbf{E}[496]$. Cosine similarity = $1.0$.
- Layers 1–6 (Syntactic Mixing): Self-attention computes keys/queries between "bank" and neighboring tokens ("account" vs "river").
- Layers 7–12 (Semantic Contextualization): Feed-forward blocks project "bank" into different geometric subspaces. Final hidden state $\vec{h}_{\text{bank}}^{\text{fin}} \neq \vec{h}_{\text{bank}}^{\text{geo}}$.
CodeMeasuring the contextual difference with BERT
The following Python code demonstrates that BERT gives "bank" genuinely different hidden states in two sentences. We extract the hidden state for the "bank" token from each sentence and compute cosine similarity — it should be well below 1.0, showing the representations have diverged.
pip install transformers torch. This downloads the BERT model weights (~440 MB) on first run. Use Google Colab or a local environment with at least 2 GB RAM.import torch
from transformers import BertTokenizer, BertModel
import torch.nn.functional as F
# ── Load model (downloads once, ~440 MB) ────────────────────────────────────
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
model = BertModel.from_pretrained("bert-base-uncased")
model.eval()
def get_token_hidden_state(sentence: str, target_word: str) -> torch.Tensor:
"""
Extract the final-layer hidden state for the first occurrence
of target_word in sentence.
Returns a 1D tensor of shape (768,).
"""
inputs = tokenizer(sentence, return_tensors="pt")
token_ids = inputs["input_ids"][0].tolist()
tokens = tokenizer.convert_ids_to_tokens(token_ids)
# Find the index of the target word token
target_idx = None
for i, tok in enumerate(tokens):
if tok == target_word.lower():
target_idx = i
break
if target_idx is None:
raise ValueError(f"'{target_word}' not found as a single token in: {tokens}")
with torch.no_grad():
outputs = model(**inputs)
# outputs.last_hidden_state shape: (1, seq_len, 768)
hidden_state = outputs.last_hidden_state[0, target_idx, :] # (768,)
return hidden_state
# ── Two sentences with "bank" ────────────────────────────────────────────────
s1 = "The bank called about my account."
s2 = "The river bank flooded last night."
h_bank_fin = get_token_hidden_state(s1, "bank") # financial context
h_bank_geo = get_token_hidden_state(s2, "bank") # geographic context
# ── Cosine similarity ────────────────────────────────────────────────────────
cos_sim = F.cosine_similarity(h_bank_fin.unsqueeze(0),
h_bank_geo.unsqueeze(0)).item()
print(f"'bank' in financial context: {h_bank_fin[:5].tolist()}...") # first 5 dims
print(f"'bank' in geographic context: {h_bank_geo[:5].tolist()}...")
print(f"\nCosine similarity between the two 'bank' vectors: {cos_sim:.4f}")
# Expected: something like 0.72 - 0.88 (well below 1.0, showing divergence)
# ── For comparison: word2vec would give cosine = 1.0 ────────────────────────
# Word2Vec: one fixed vector. Same vector = cosine similarity = 1.0.
# Static embeddings cannot distinguish these two contexts at all.
What this demonstrates
The cosine similarity between BERT's two "bank" vectors is noticeably below 1.0 — the representations have diverged because attention has incorporated context. A static word2vec vector would give exactly 1.0 (identical vectors).
What to try next
Test with "bat" (animal/cricket), "light" (noun/verb/adjective), "lead" (metal/verb). Also try changing the sentence structure slightly and observe how much the hidden state shifts even for small context changes.
Hands-OnPolysemy exploration experiments
🔬 Three experiments to run
These experiments build intuition for how much context shifts representations.
Experiment 1: "light" in three roles
Experiment 2: "lead" across roles
Experiment 3: Static vs contextual ranking comparison
CompareStatic vs contextual — full table
| Aspect | Static (Word2Vec / GloVe / FastText) | Contextual (BERT / GPT / T5) |
|---|---|---|
| Vector depends on context? | No. Fixed for each token type, regardless of sentence. | Yes. Hidden state changes with every different sentence. |
| Polysemy handling | Averages over all senses. "bank" = blend of all uses. | Separates senses via context. "bank" after "river" ≠ "bank" after "account". |
| Computation at inference | Table lookup only — O(1) per token. Extremely fast. | Full forward pass through all attention layers — O(n²) per layer. Significantly more compute. |
| Memory | Small — just the embedding matrix (e.g. 300d × 1M words ≈ 1.2 GB). | Full model weights — BERT-base ~440 MB, LLaMA-7B ~13 GB, GPT-4 much larger. |
| Sentence-level understanding | None inherent — each token is independent of others. | Full — each token attends to all others; global context is captured. |
| Training required | Train once on corpus. Reusable for any downstream task without fine-tuning. | Pretrained on large corpus. Fine-tuning often needed for downstream tasks. |
| Best for | Simple word similarity, document classification with bag-of-words, fast retrieval without a full model. | NER, QA, classification, translation, coreference — any task needing sentence-level understanding. |
| Examples | Word2Vec, GloVe, FastText, ELMo (semi-contextual) | BERT, RoBERTa, GPT-2/3/4, T5, LLaMA, Mistral, Claude |
ApplyWhere contextual representations change everything
Contextual embeddings are the engine behind most modern NLP systems. Here are four areas where the context-dependent nature of the representation is not just helpful — it is required.
Named Entity Recognition (NER)
A static embedding cannot distinguish "Washington" the person from "Washington" the location — both map to the same vector. BERT's contextual representation shifts based on surrounding words ("President Washington" vs "Washington D.C."), enabling correct entity classification.
Question Answering (QA)
Pronouns and coreferences ("he", "it", "the company") require understanding what each token refers to across the full sentence or paragraph. Contextual hidden states capture these dependencies; static embeddings cannot.
Semantic Search (SBERT)
Sentence Transformers (SBERT) pool BERT's contextual token representations into a sentence embedding. This gives you a single vector that captures sentence meaning — not just word overlap — enabling much richer retrieval than keyword or TF-IDF search.
Machine Translation
Word sense disambiguation is a known hard problem in translation. "The bank approved the loan" vs "the fish jumped on the bank" must produce completely different translations for "bank" in many languages. Contextual representations give the system that information.
The BridgeWhy attention is not optional — it is the mechanism
Here is the key insight that ties the entire vectors roadmap to the attention roadmap. The reason contextual embeddings require attention is not arbitrary design — attention is precisely the mechanism that allows a token's representation to be influenced by its neighbours.
Without attention:
- Each token's representation would remain fixed at its static embedding after lookup.
- "bank" after "river" would look identical to "bank" after "account".
- There would be no mechanism for polysemy resolution, coreference, or any sentence-level understanding.
With attention:
- Each token computes a weighted sum over all other tokens' representations, weighted by relevance (query–key dot products).
- A token like "bank" after "river" will put high attention weight on "river", pulling its representation toward the geographic sense.
- After multiple layers, the hidden state has incorporated rich contextual information from the entire sequence.
- Static embedding = what the token is (its identity from the lookup table).
- Contextual hidden state = what the token means here (identity + all surrounding context, processed through attention).
- Attention is the mathematical mechanism that computes the difference between these two.
This is the complete conceptual bridge. The entire Attention branch of the AI Journey roadmap is about how this transformation happens — how query/key/value matrices are formed, how attention scores are computed and normalised, how multi-head attention captures multiple relationship types simultaneously, and how all of this stacks into a transformer.
→ Continue to the Attention Roadmap
You've reached the conceptual boundary between the Vectors topic and the Attention topic. Everything from this point — how attention weights are computed, why $\text{softmax}(QK^T/\sqrt{d_k})V$ works, multi-head attention, positional encodings, transformer architecture — is covered in the Attention roadmap.
Start: Attention Roadmap →Feynman ChallengeExplain it without using "embedding" or "vector"
Explain static vs contextual representations to someone who knows nothing about machine learning. Use the "name tag vs identity badge" analogy:
- Imagine every word has a name tag (static embedding). The name tag says "bank" and is the same everywhere — doesn't matter if you're at a river or at a financial institution.
- Now imagine an identity badge that also shows what you're doing today — your job title, department, current project. That's the contextual representation. "bank" working at the geography department next to the river has a completely different badge from "bank" working at the finance department next to the vault.
- Static embeddings are name tags. Contextual representations are identity badges that update based on who's around you and what's happening.
- Attention is the system that reads the room and updates the badge accordingly.
Common misconceptions to tackle:
- "BERT has no static embeddings — it's all contextual." Wrong. BERT absolutely has a static embedding table. Every token still starts as a fixed vector from that table. Attention then builds on top of it.
- "Contextual is always better than static." Depends on the task. For fast retrieval over millions of documents, static embeddings require no forward pass. For meaning-sensitive tasks, contextual wins.
- "I can compare contextual embeddings from different models directly." No. Contextual hidden states are not interoperable across models — different architectures, different training, different representation spaces.
- "The initial embedding table is useless once attention runs." No. The embedding table is the foundational input. Its quality shapes the entire representation that attention builds on. Bad initial embeddings make the transformer's job harder.
- "Word2Vec is obsolete and wrong." It's limited for contextual tasks, but not wrong — it's a fast, compact representation that's still useful for many similarity and retrieval tasks where a full transformer forward pass is too expensive.
Build + SummaryCement your understanding
🔨 Mini-Projects
1 · Polysemy explorer
Choose 5 polysemous words (bank, bat, light, lead, spring). Build 3 sentences each with different senses. Extract BERT's last-layer hidden state for the target token in each sentence. Compute the full pairwise cosine similarity matrix (3×3 per word). Visualise which contexts diverge most. Which words show the largest spread?
2 · Static vs contextual similarity comparison
Take 20 word pairs (e.g. bank-finance, bank-river, cat-dog, cat-feline). Rank them by similarity using word2vec cosine. Then rank them by BERT contextual cosine (using a neutral sentence for each word). Count rank inversions between the two lists. What does each ranking reveal that the other misses?
3 · Attention attribution
Use BertViz or manually extract attention weights from BertModel(output_attentions=True). For "The bank approved the loan" and "The river bank flooded", plot which tokens "bank" attends to most at layer 6, head 3. Observe how attention weight concentrations differ between the two sentences.
Summary
→ Ready for the Attention Roadmap?
You understand why attention is needed. The next roadmap explains how it works: queries, keys, values, scaled dot-product attention, multi-head attention, and the full transformer architecture.
Start: Attention Roadmap →