Explain the concept of contextual embeddings. How do models like BERT generate contextual embeddings, and in what scenarios are they advantageous compared to traditional word embeddings?
Contextual embeddings assign a dynamic vector representation to each subword token based on its surrounding sentence or document rather than a single static lookup vector. Encoder models like BERT compute these representations through stacked bidirectional self-attention layers, integrating syntax and semantic cues from both left and right context. This resolves polysemy and enables superior performance on tasks like question answering, named entity recognition, and natural language inference.
Study Card: Contextual Embeddings
Direct Answer
Contextual embeddings generate a distinct vector representation for each token conditioned on its full sequence context, rather than assigning a single fixed vector per word type like Word2Vec or GloVe.
Models such as BERT compute contextual embeddings in three stages:
- Subword Tokenization & Initial Embedding: Input text is split into subwords (e.g., WordPiece or BPE), and each token receives an initial embedding summing token, positional, and optional segment embeddings.
- Stacked Self-Attention Layers: Across Transformer encoder blocks, every token exchanges information with all other tokens via bidirectional self-attention:
- Layer-Wise Specialization: Lower Transformer layers primarily encode lexical identity and local syntax, while middle and upper layers encode long-range coreference, semantic roles, and context-specific word sense.
Unlike bidirectional encoders (BERT, RoBERTa), causal decoder LLMs (GPT, LLaMA) compute left-contextualized embeddings because causal masking blocks future tokens. Contextual embeddings excel at polysemy disambiguation, named entity recognition (NER), extractive QA, and semantic entailment.
Key Terms
- Contextual Embeddings: Dynamic hidden-state vectors for each token occurrence that shift based on surrounding context.
- Static Word Embeddings: Context-free vocabulary lookup vectors (e.g., Word2Vec, GloVe) where all senses of a word collapse into one vector.
- Subword Tokenization (WordPiece / BPE): Splits rare or compound words into subword units so embeddings handle unseen vocabulary without
<UNK>collapse. - Bidirectional Self-Attention: Encoder attention allowing each position to attend simultaneously to both preceding and succeeding tokens.
Example
Consider the polysemous word "bank" in two sentences:
"I deposited cash at the bank yesterday."self-attention links"bank"strongly to"deposited"and"cash", shifting its hidden representation toward the financial institution subspace."We sat quietly along the river bank."self-attention links"bank"to"river"and"along", shifting the vector toward the geography/shoreline subspace.
A static Word2Vec table returns the exact same vector for "bank" in both sentences, whereas BERT produces clearly separated contextual vectors.
Code Implementation
import torch
import torch.nn.functional as F
from transformers import BertConfig, BertModel
def extract_token_embedding(hidden_states, input_ids, target_token_id):
"""Safely extracts the first occurrence of target_token_id without failing on duplicates."""
matches = (input_ids[0] == target_token_id).nonzero(as_tuple=True)[0]
if matches.numel() == 0:
raise ValueError(f"Token ID {target_token_id} not found in sequence.")
return hidden_states[0, matches[0].item()]
# In production, load pretrained weights & tokenizer:
# tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
# model = BertModel.from_pretrained("bert-base-uncased")
# Here we build a compact BertModel offline to demonstrate dynamic contextualization:
torch.manual_seed(42)
cfg = BertConfig(vocab_size=500, hidden_size=64, num_hidden_layers=2, num_attention_heads=4, intermediate_size=128)
model = BertModel(cfg)
model.eval()
# Token ID 42 represents the ambiguous word "bank" appearing in two distinct contexts
BANK_ID = 42
sent_finance = torch.tensor([[101, 12, 15, BANK_ID, 20, 21, 102]]) # "I deposited money at bank"
sent_river = torch.tensor([[101, 30, 31, 32, BANK_ID, 33, 102]]) # "We sat by the river bank"
with torch.no_grad():
h_fin = model(input_ids=sent_finance).last_hidden_state
h_riv = model(input_ids=sent_river).last_hidden_state
vec_fin = extract_token_embedding(h_fin, sent_finance, BANK_ID)
vec_riv = extract_token_embedding(h_riv, sent_river, BANK_ID)
# Static input embedding is identical for token 42; contextual output vectors diverge!
static_vec = model.embeddings.word_embeddings.weight[BANK_ID]
cos_ctx = F.cosine_similarity(vec_fin, vec_riv, dim=0).item()
print("Static embedding identical? True | Contextual output shape:", vec_fin.shape)
print(f"Contextual cosine similarity of token {BANK_ID} across contexts: {cos_ctx:.4f}")
Related Concepts
- Static Embeddings (Word2Vec & GloVe): Fast, low-compute representations still useful for lightweight lexical baselines or input layers, though blind to word order and sense.
- ELMo: Pioneering bidirectional LSTM contextual representation replaced largely by parallelizable Transformers.
- Bidirectional vs. Causal Context: Encoders (BERT) capture full bidirectional context; decoder LLMs (GPT/LLaMA) produce causal embeddings conditioned only on prior tokens.
- Pooling for Sentence Embeddings: Aggregating contextual token states via attention-masked mean pooling (paired with contrastive training) creates strong passage vectors.