Compare and contrast word embeddings and sentence embeddings. How do their applications differ, and what considerations come into play when choosing between them?
Word embeddings map individual word types to static dense vectors that capture lexical similarity but collapse polysemous senses into a single representation. Sentence embeddings encode entire sentences or passages into fixed-dimensional vectors that reflect word order, syntax, and compositional semantics. Word embeddings suit lexical tasks or sequence model inputs, whereas contrastively trained sentence embeddings power semantic search, clustering, and retrieval-augmented generation.
Study Card: Word Embeddings vs. Sentence Embeddings
Direct Answer
Word embeddings (such as Word2Vec, GloVe, and FastText) represent individual vocabulary tokens as static dense vectors learned from local co-occurrence statistics. Sentence embeddings (such as Sentence-BERT, E5, BGE, or Universal Sentence Encoder) map variable-length sentences, queries, or documents into a single fixed-dimensional vector capturing overall compositional meaning.
Key trade-offs when choosing between them:
- Context & Polysemy: Static word embeddings assign one vector per word type regardless of context (unable to distinguish
"river bank"from"bank account"). Sentence encoders use self-attention across tokens to disambiguate meaning, word order, and negation. - Out-of-Vocabulary (OOV) Handling: Word2Vec/GloVe fail on unseen words (FastText mitigates this with subword character -grams), while modern transformer sentence embedders use BPE/WordPiece subword tokenizers.
- Compositionality: Simply averaging word embeddings (or naive averaging of raw BERT token outputs without contrastive fine-tuning) loses word order and suffers from representation anisotropy; dedicated bi-encoder sentence models trained with contrastive objectives outperform unweighted averages on semantic retrieval.
- Latency vs. Granularity: Precomputed sentence embeddings allow fast Approximate Nearest Neighbor (ANN) vector search over millions of passages, whereas token-level or cross-encoder models trade higher compute for finer-grained matching.
Key Terms
- Static Word Embeddings: Context-independent token lookup tables (e.g., Word2Vec, GloVe, FastText) trained via skip-gram, CBOW, or matrix factorization.
- Sentence Embeddings: Fixed-size passage vectors produced by pooling transformer representations (e.g., mean pooling or
[EOS]/[CLS]extraction) after contrastive bi-encoder training. - Bi-Encoder vs. Cross-Encoder: Bi-encoders embed query and document independently for fast cosine/dot-product search, while cross-encoders jointly attend across both texts at higher compute cost.
- Anisotropy: A geometric failure mode in raw language model embeddings where vectors cluster in a narrow cone, degrading cosine similarity until fixed by contrastive fine-tuning.
Example
Suppose you want to measure lexical similarity for "happy"—a static word embedding space directly surfaces nearest neighbors such as "joyful" or "cheerful". However, suppose you compare "The dog chased the cat" against "The cat chased the dog": averaging static word vectors produces the exact same sentence vector for both opposite meanings because addition is commutative.
A contrastively trained transformer sentence embedding encodes syntactic roles (subject vs. object) via self-attention and positional encodings, producing distinct embeddings suitable for retrieval-augmented generation (RAG), semantic deduplication, and paraphrase detection.
Code Implementation
import numpy as np
import torch
import torch.nn.functional as F
# 1. Word Embeddings (static lookup table, e.g., Word2Vec / nn.Embedding)
vocab = {"cat": 0, "sat": 1, "mat": 2, "dog": 3, "chased": 4, "ball": 5}
torch.manual_seed(42)
word_table = F.normalize(torch.randn(len(vocab), 64), p=2, dim=-1)
def bag_of_words_average(sentence: str) -> torch.Tensor:
tokens = [vocab[w] for w in sentence.lower().split() if w in vocab]
vecs = word_table[tokens]
return F.normalize(vecs.mean(dim=0), p=2, dim=-1)
# Notice order blindness of averaged static word embeddings:
s1_bow = bag_of_words_average("dog chased cat")
s2_bow = bag_of_words_average("cat chased dog")
print("Averaged word-embedding cosine sim (order-blind):", F.cosine_similarity(s1_bow, s2_bow, dim=0).item())
# 2. Sentence Embeddings (Bi-encoder pooling pattern, e.g., SentenceTransformer)
# In production, load a contrastively trained bi-encoder:
# from sentence_transformers import SentenceTransformer
# sent_model = SentenceTransformer("all-mpnet-base-v2")
# embs = sent_model.encode(["The dog chased the cat.", "The cat chased the dog."], normalize_embeddings=True)
#
# Here we simulate token-level attention masking + mean pooling over a transformer hidden state:
token_hidden_states = torch.randn(2, 6, 128) # (batch=2, seq_len=6, hidden_dim=128)
attention_mask = torch.tensor([[1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 0, 0]], dtype=torch.float32)
mask_expanded = attention_mask.unsqueeze(-1)
pooled = (token_hidden_states * mask_expanded).sum(dim=1) / mask_expanded.sum(dim=1).clamp(min=1e-9)
sentence_embeddings = F.normalize(pooled, p=2, dim=-1)
sim = F.cosine_similarity(sentence_embeddings[0], sentence_embeddings[1], dim=0)
print("Pooled sentence embedding shape:", sentence_embeddings.shape)
print("Simulated sentence cosine similarity:", round(sim.item(), 4))
Related Concepts
- Word2Vec, GloVe, FastText: Classical static word vector algorithms differing in local predictive objectives vs. global co-occurrence factorization vs. character -grams.
- Sentence-BERT (SBERT), E5, BGE: Modern bi-encoder architectures using Siamese/contrastive InfoNCE training with in-batch and hard negatives.
- Late Interaction (ColBERT): Bridges word and sentence embeddings by retaining per-token embeddings for MaxSim matching while remaining indexable.
- Cosine Similarity & Normalization: Standard similarity metric on L2-normalized embedding spaces where cosine similarity reduces to dot product.
- MTEB Benchmark: Standard multi-task suite evaluating sentence embeddings across retrieval, reranking, clustering, classification, and STS.