Charan | AI Journey › 01 · Vectors › Static vs Contextual
⚡ 3D Simulator
AI Journey · Vectors → Attention Bridge

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.

🟡 GOOD 15 Study Phases Vectors Prerequisite: How Embeddings Are Learned → Vector Space
🧙‍♂️ The Wise Scholar's Metaphor The Base Meaning vs. Active Sentence Coloring
⏮️ 00 · Math & Foundations Hub →

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!

01

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".

Key idea:
  • 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.
Token ID→ Embedding table lookup→ Static vector (fixed) → Attention layers→ Contextual hidden state
02

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).

Key idea: Polysemy (one word, many meanings) is the core problem that static embeddings cannot fully solve. Static embeddings average out the senses; contextual embeddings can separate them using surrounding words as evidence.
Downstream impact: In named entity recognition (NER), a model using only static embeddings cannot distinguish "Washington" (George Washington, person) from "Washington" (Washington D.C., location) — both map to the same vector. Contextual representations fix this.
03

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.

Important nuance: The token ID still selects the same row in the embedding table — that initial static embedding is the starting point. The contextual representation is produced after attention has operated on top of that starting point. The two are layers of the same pipeline, not alternatives.
04

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.

MethodTraining objectiveKey insightLimitation
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.
At inference: 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.

05

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.

step 1 Look up static embedding: $e_i = E[t_i]$ — same for "bank" regardless of context.
step 2 Add positional encoding: $x_i = e_i + \text{PE}(i)$ — tells the model where in the sequence the token is.
step 3 Pass through $L$ attention layers: $h_i^{(\ell)} = \text{Attention}(h_i^{(\ell-1)},\; h_{1..n}^{(\ell-1)})$ — each token attends to all others.
result Final hidden state $h_i^{(L)}$ is contextual. "bank" in "river bank" → different $h_i$ than "bank" in "bank account".
Simplified intuition: $h_i = \text{Attention}(E[t_i],\; E[t_{1..n}])$ — the contextual representation of token $i$ is a function of its static embedding AND all other tokens' embeddings, weighted by relevance.

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.

06

How It WorksFrom token to contextual representation

The full pipeline from raw text to contextual hidden state, step by step:

Raw text→ Tokenize→ Token IDs→ Embedding table→ Static vectors→ + Positional encoding→ Attention layer 1→ …→ Attention layer N→ Contextual hidden states
  1. Tokenize: Split raw text into tokens (WordPiece, BPE, SentencePiece…).
  2. Token ID lookup: Convert tokens to integer IDs using the vocabulary.
  3. Embedding table lookup: Each ID indexes one row in the embedding matrix $E \in \mathbb{R}^{V \times d}$. This is the static embedding.
  4. Positional encoding: Add position information — transformer has no inherent notion of order.
  5. Attention layers: Each layer computes attention scores between all token pairs, allowing each token's representation to be updated based on context.
  6. Output: Final hidden states — one $d$-dimensional vector per token, fully contextual. These are what downstream tasks use.
Key insight: The static embedding is the input to the transformer, not the output. The contextual representation only exists after the attention layers have run. Skipping straight from token IDs to "contextual embeddings" is a conceptual shortcut — the attention mechanism is what creates them.
07

Worked Example"bank" in two sentences

Consider the word "bank" in two sentences with completely different meanings. We trace what happens at each layer.

input 1 "The bank called about my account." — financial context. Tokens: [The, bank, called, about, my, account, .]
input 2 "The river bank flooded last night." — geographic context. Tokens: [The, river, bank, flooded, last, night, .]
static E[bank] Identical for both sentences: [0.12, −0.41, 0.77, …] (same row in embedding table). No difference yet.
after layer 1 Sentence 1: "bank" has now attended to "account" (strong financial signal) → representation shifts toward financial domain.
Sentence 2: "bank" has now attended to "river" (strong geographic signal) → representation shifts toward geographic domain.
final h[bank] Sentence 1: $h_{\text{bank}}^{\text{fin}} \approx [0.54, 0.12, −0.33, …]$ — financial context vector.
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.
Note: The exact numbers above are illustrative. The key point is that the final hidden states for "bank" in these two sentences will differ in a well-trained model — the two contexts pull the representation in different directions.
08

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.

flowchart TB subgraph Sentence1["Sentence 1: The bank called about my account"] S1T["Tokens: The | bank | called | about | my | account"] S1E["Static embed(bank) = [0.12, -0.41, 0.77, ...]"] S1A["Attention: bank ←→ account (strong)"] S1H["h_bank = financial-domain vector"] S1T --> S1E --> S1A --> S1H end subgraph Sentence2["Sentence 2: The river bank flooded last night"] S2T["Tokens: The | river | bank | flooded | last | night"] S2E["Static embed(bank) = [0.12, -0.41, 0.77, ...]"] S2A["Attention: bank ←→ river (strong)"] S2H["h_bank = geographic-domain vector"] S2T --> S2E --> S2A --> S2H end S1E -. "same initial vector" .- S2E S1H -. "measurably different" .- S2H

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.

🎭 Live Lab: Polysemy & Contextual Shift Visualizer
Watch Static Word2Vec (1 Fixed Vector) vs. Contextual Transformer (Dynamic Divergence)
Context A: Financial
"The bank called about my money and account."
Final Shift: [+0.82, +0.55] → Financial Sector
Context B: Nature / River
"The muddy river bank flooded after rain."
Final Shift: [-0.78, +0.62] → Geography Sector
Static Word2Vec Cosine Distance
$\cos(\vec{v}_A, \vec{v}_B) = 1.000$
Exact same row lookup. Blind to polysemy!
Contextual Transformer Divergence
$\cos(\vec{h}_A, \vec{h}_B) = 0.284$
Attention weights shifted vectors to distinct domains!
🔍 Behind-the-Scenes: The Layer-by-Layer Attention Transformation

How a 12-layer Transformer separates identical word tokens:

  1. Layer 0 (Static Input): Both sentences retrieve identical static vector $\vec{e}_{\text{bank}} = \mathbf{E}[496]$. Cosine similarity = $1.0$.
  2. Layers 1–6 (Syntactic Mixing): Self-attention computes keys/queries between "bank" and neighboring tokens ("account" vs "river").
  3. 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}}$.
09

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.

Dependencies required: 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.
Python
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.

10

Hands-OnPolysemy exploration experiments

🔬 Three experiments to run

These experiments build intuition for how much context shifts representations.

Experiment 1: "light" in three roles

$Sentence A: "The light is bright in here." (noun — illumination)
$Sentence B: "The bag feels very light." (adjective — not heavy)
$Sentence C: "Please light the candle." (verb — to ignite)
→Compare: cosine(A,B), cosine(B,C), cosine(A,C)
→Expect: all three to be <1.0; verb (C) likely furthest from noun (A)

Experiment 2: "lead" across roles

$Sentence A: "He will lead the team next quarter." (verb: guide)
$Sentence B: "The pipe is made of lead." (noun: metal)
$Sentence C: "She plays lead guitar." (adjective: primary)
→Note: tokenizer may split "lead" differently in some sentences

Experiment 3: Static vs contextual ranking comparison

$Pick 10 polysemous words.
$For each, build 2 sentences in different semantic roles.
$Word2Vec: cosine(bank_vec, bank_vec) = 1.0 always.
$BERT: cosine varies — reveals which words are most disambiguated by context.
→Rank words by BERT cosine: lower = more context-dependent
11

CompareStatic vs contextual — full table

AspectStatic (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
Neither is always better: For a fast similarity search over millions of documents, static embeddings are often the right choice — no transformer forward pass needed. For tasks that require understanding meaning-in-context, contextual embeddings are essential.
12

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.

Modern default: Almost all state-of-the-art NLP systems use contextual representations (transformer-based) as their backbone. Static embeddings are primarily used when compute efficiency is critical or as the starting layer inside a larger transformer.
13

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.
The core equation:
  • 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 →
14

Feynman ChallengeExplain it without using "embedding" or "vector"

Feynman Mastery Check

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.
10-second explanation: Static embeddings give every word a fixed number regardless of context. Contextual representations use the surrounding words (via attention) to update that number so the model can tell that "bank" next to "river" means something different from "bank" next to "account".

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.
15

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

Static One fixed vector per token type (Word2Vec, GloVe, FastText). Fast. No context. Polysemy averaged out.
Contextual Token representation updated by attention over all neighbours (BERT, GPT). Polysemy resolved. More compute.
The pipeline Token ID → embedding table (static) → + positional encoding → attention layers → contextual hidden state.
The bridge Attention is the mechanism that converts static inputs into contextual outputs. The Attention roadmap covers exactly how.

→ 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 →
🐙
Go Deeper · Code it yourself
ai-engineering-from-scratch
523 lessons, open source. Static embeddings are the starting point — this lesson implements self-attention from scratch so you see exactly how context transforms those fixed vectors into dynamic ones.
This page 0:00
This session 0:00
Total (all pages) 0:00
Today 0:00
▶ Running
📊 View all study stats →
0:00 studying