Sub topic 11
Contextual embeddings and cosine similarity
BLEU and ROUGE count exact matches between words or n-grams. A candidate that says "sitting on the rug" gets no credit against a reference that says "sat on the mat", even though the meaning is close. BERTScore, covered in the next chapter, addresses this by comparing tokens as vectors instead of as strings. This chapter covers the two building blocks it needs: contextual token embeddings, and cosine similarity as the measure of how close two vectors are.
This chapter assumes you can read basic Python and NumPy or PyTorch code. It also assumes you know roughly what a word embedding is and what a transformer encoder does. You do not need to know how attention works internally.
From static to contextual embeddings
A static embedding, such as word2vec or GloVe, assigns one vector to each word type. The word "bank" has the same vector in "river bank" and in "bank account". The vector ends up as a blend of every sense the word had in the training data.
A contextual embedding is computed by running the whole sentence through a model such as BERT or RoBERTa. Each token gets its own vector, and that vector depends on the tokens around it. The same word in two different sentences gets two different vectors.
| Property | Static embedding | Contextual embedding |
|---|---|---|
| Lookup key | Word type | Token in a specific sentence |
| Same word, different sentence | Identical vector | Different vector |
| Handles polysemy (multiple senses) | Poorly | Reasonably well |
| Cost | Table lookup | One forward pass of a transformer |
| Unit | Whole words | Subword tokens |
The last row has consequences for metrics. Transformer models split text into subword pieces. In bert-base-uncased, a rare word like "unhappiness" may become un, ##happi, ##ness. Every vector therefore belongs to a piece, not necessarily a whole word. Special tokens such as [CLS] and [SEP] also get vectors, and metric code usually has to decide whether to keep them.
Getting token vectors from a model
The Hugging Face transformers library returns the vectors in last_hidden_state, a tensor of shape (batch, tokens, hidden size). For bert-base-uncased the hidden size is 768.
The script below extracts the vector for the token "bank" in three sentences. Two use the financial sense and one uses the river sense.
import torch
from transformers import AutoTokenizer, AutoModel
name = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModel.from_pretrained(name)
model.eval()
def token_vectors(sentence):
inputs = tokenizer(sentence, return_tensors="pt")
with torch.no_grad():
output = model(**inputs)
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
return tokens, output.last_hidden_state[0]
def vector_for(sentence, word):
tokens, vectors = token_vectors(sentence)
return vectors[tokens.index(word)]
river = vector_for("she sat on the bank of the river", "bank")
money_a = vector_for("she deposited cash at the bank", "bank")
money_b = vector_for("he opened an account at the bank", "bank")
cosine = torch.nn.functional.cosine_similarity
print("river vs money:", cosine(river, money_a, dim=0).item())
print("money vs money:", cosine(money_a, money_b, dim=0).item())The second number is normally higher than the first, because the model encodes the financial sense differently from the river sense. A static embedding would give 1.0 for both comparisons, since it would return the same vector each time. The exact values depend on the model version, so compare the two numbers to each other and do not expect specific values.
Calling model.eval() and wrapping the forward pass in torch.no_grad() matters here. Evaluation mode turns off dropout, which would otherwise add random noise to the vectors and make scores differ between runs. Disabling gradients saves memory.
Cosine similarity
Cosine similarity measures the angle between two vectors and ignores their lengths:
cos(u, v) = (u · v) / (‖u‖ ‖v‖)
The numerator is the dot product. The denominator is the product of the two vector lengths (L2 norms). The result lies between -1 and 1:
- 1 means the vectors point in the same direction.
- 0 means they are orthogonal (unrelated in direction).
- -1 means they point in opposite directions.
Here is the formula written out in NumPy, so nothing is hidden behind a library call.
import numpy as np
def cosine_similarity(u, v):
return float(np.dot(u, v) / (np.linalg.norm(u) * np.linalg.norm(v)))
a = np.array([1.0, 2.0, 3.0])
b = np.array([2.0, 4.0, 6.0]) # same direction as a, twice as long
c = np.array([3.0, 0.0, -1.0]) # a . c = 0, so orthogonal to a
print(cosine_similarity(a, b)) # 1.0 (up to floating-point rounding)
print(cosine_similarity(a, c)) # 0.0The vector b is twice as long as a but scores 1.0. That is the point of the metric. In embedding spaces, vector length often reflects things unrelated to meaning, such as how frequent a token is. Ignoring length keeps the comparison focused on direction.
Why normalize first
If you divide every vector by its own norm once, cosine similarity becomes a plain dot product. This is how metric implementations compare many token pairs at once, because a dot product between two sets of vectors is one matrix multiplication.
import torch
vec_a = torch.tensor([[1.0, 2.0, 3.0], [0.0, 1.0, 0.0]]) # 2 tokens
vec_b = torch.tensor([[2.0, 4.0, 6.0], [3.0, 0.0, -1.0], [0.0, 5.0, 0.0]]) # 3 tokens
unit_a = torch.nn.functional.normalize(vec_a, dim=1)
unit_b = torch.nn.functional.normalize(vec_b, dim=1)
similarity = unit_a @ unit_b.T # shape (2, 3): every token in A against every token in B
print(similarity)The result has one row per token in the first sentence and one column per token in the second. Entry (i, j) is the cosine similarity between token i of A and token j of B. The next chapter's greedy matching operates on exactly this matrix: for each row it takes the best column, and for each column it takes the best row.
A token-level similarity matrix for two sentences
Combining the two pieces gives the raw material for BERTScore. The function below embeds two sentences, drops the special tokens, normalizes, and returns a similarity matrix with labeled tokens.
import torch
from transformers import AutoTokenizer, AutoModel
name = "bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModel.from_pretrained(name)
model.eval()
def content_vectors(sentence):
inputs = tokenizer(sentence, return_tensors="pt")
with torch.no_grad():
hidden = model(**inputs).last_hidden_state[0]
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
# Drop [CLS] (first) and [SEP] (last).
return tokens[1:-1], hidden[1:-1]
cand_tokens, cand_vecs = content_vectors("the cat sat on the mat")
ref_tokens, ref_vecs = content_vectors("a cat was sitting on the rug")
cand_unit = torch.nn.functional.normalize(cand_vecs, dim=1)
ref_unit = torch.nn.functional.normalize(ref_vecs, dim=1)
matrix = cand_unit @ ref_unit.T
print("columns:", ref_tokens)
for token, row in zip(cand_tokens, matrix):
best = row.argmax().item()
print(f"{token:>5} -> best match {ref_tokens[best]!r} ({row[best].item():.3f})")You should see "cat" align with "cat", "on" with "on", and "mat" most likely with "rug". This shows how contextual vectors can give partial credit to near-synonyms, which exact matching cannot do.
Choices that change the numbers
Several decisions sit between "I have a model" and "I have a similarity score". Each can shift results.
- Which model. A multilingual model for non-English text, a larger model for finer distinctions. Scores from different models are not comparable.
- Which layer. The last layer is the default in
last_hidden_state, but intermediate layers often carry more lexical and syntactic information. Metric libraries sometimes use a middle layer for exactly this reason, so do not assume the final layer is best. - Special tokens.
[CLS]and[SEP]carry sentence-level information rather than word meaning. Whether they are included changes the scores. - Subword handling. Matching happens on pieces such as
##ness, not on words. A word split into three pieces has three times the influence of a one-piece word unless something corrects for that. - Maximum length. BERT-style models accept at most 512 tokens. Longer inputs are truncated or must be split, which affects long-document summarization.
Common errors
- Comparing vectors from different models. The spaces are unrelated, so the similarity is meaningless. Both sides must come from the same model and layer.
- Forgetting
eval(). Dropout stays active and scores vary run to run. - Looking up a word that was split.
tokens.index("unhappiness")raises aValueErrorbecause the tokenizer produced pieces. Search the token list for the actual pieces, or map words to pieces with the tokenizer'sword_ids()on a fast tokenizer. - Mixing padded batches without a mask. When you embed several sentences at once, padding tokens get vectors too. Use the
attention_maskto exclude them, or you will match against padding. - Reading cosine as a probability. It is a geometric quantity, not a calibrated score.
Exercise
Two vectors are u = [3, 4] and v = [6, 8]. What is their cosine similarity, and what does the result say about using vector length when comparing embeddings?
Show answer
The dot product is 36 + 48 = 50. The norms are 5 and 10, so the denominator is 50 and the cosine similarity is 1.0. The vectors point in the same direction even though v is twice as long, so cosine similarity ignores length and compares direction only.
Exercise
You embed a candidate with 6 tokens and a reference with 7 tokens, after removing [CLS] and [SEP]. After normalizing the vectors, what is the shape of the similarity matrix produced by candidateunit @ referenceunit.T, and what does entry (2, 5) represent?
Show answer
The shape is (6, 7). Entry (2, 5) is the cosine similarity between the third candidate token and the sixth reference token, using zero-based indexing. Normalizing first means the matrix product gives cosine similarities directly.
Exercise
A colleague reports that a BERT-based comparison of two unrelated sentences gave an average token cosine similarity of 0.45 and concludes the sentences are "45% similar". Explain what is wrong with that reading.
Show answer
Contextual embeddings are anisotropic: they occupy a narrow cone, so even unrelated tokens often have high cosine similarity. Cosine is also a geometric quantity, not a percentage of shared meaning. The value is only useful in comparison with other scores from the same model and layer, or after a baseline correction such as BERTScore's rescaling.