Sub topic 14
GloVe: fitting log co-occurrence counts
This chapter assumes you know the co-occurrence matrix from the previous chapter, can read a least-squares loss, and understand gradient descent. It covers the GloVe objective, why it has its shape, how the weighting function works, and where implementations go wrong.
The idea in one paragraph
word2vec learns vectors by predicting context words, one window at a time. GloVe (Global Vectors, Pennington, Socher and Manning, 2014) first collects the whole corpus into a co-occurrence table. It then fits vectors so that the dot product of two word vectors approximates the logarithm of how often the words co-occur. Training is a weighted regression on table entries. It does not slide over text.
Notation
X_ijis the (weighted) count of wordjappearing in the context of wordi.X_i = Σ_k X_ikis the total count for wordi.P_ij = X_ij / X_iis the probability thatjappears in the context ofi.- Each word has two vectors: a word vector
w_iand a context vectorw̃_j. Each also has a scalar bias,b_iandb̃_j.
Why ratios, and where the log comes from
Raw probabilities are noisy signals of meaning. Ratios of probabilities are more informative. Take i = ice and j = steam. For a probe word k = solid, P(k|ice) / P(k|steam) is large. For k = gas it is small. For k = water, which relates to both, or k = fashion, which relates to neither, the ratio is near 1. The ratio separates the relevant words from the noise.
GloVe therefore asks for vectors whose differences predict these ratios. The paper requires a function F such that:
F((w_i − w_j)ᵀ w̃_k) = P_ik / P_jk
If F turns subtraction into division, then F = exp. This gives w_iᵀ w̃_k = log P_ik = log X_ik − log X_i.
The term log X_i does not depend on k, so a bias b_i absorbs it. The expression should also be symmetric in the two roles, so a second bias b̃_k is added. The result is:
w_iᵀ w̃_j + b_i + b̃_j ≈ log X_ij
The objective
Turning that approximation into a least-squares problem, with a weight per entry, gives:
J = Σ_{i,j: X_ij>0} f(X_ij) · (w_iᵀ w̃_j + b_i + b̃_j − log X_ij)²
The weighting function is:
f(x) = (x / x_max)^α if x < x_max, otherwise 1
The published defaults are x_max = 100 and α = 0.75. The weight does two jobs:
- It silences rare pairs. A pair seen once or twice is mostly noise. Its weight is small, so it barely affects the fit.
- It caps frequent pairs. Pairs like ("the", "of") would otherwise dominate the loss. Past
x_maxthey all count equally.
| Count `x` | `f(x)` with `x_max=100`, `α=0.75` |
|---|---|
| 1 | 0.032 |
| 10 | 0.178 |
| 100 | 1.0 |
| 1000 | 1.0 |
The sum runs only over nonzero entries, because log 0 is undefined. The weighting function also has f(0) = 0, which is consistent with skipping those entries. This makes training cost proportional to the number of nonzero cells, not to V².
A runnable implementation
The code below reuses the 1/distance co-occurrence counting from the previous chapter. It then fits the GloVe objective with plain SGD. The real GloVe tool uses AdaGrad and a much larger corpus. This version is meant to show the objective, not to produce good vectors.
import numpy as np
from collections import defaultdict
def cooccurrence(sentences, window=2):
counts = defaultdict(float)
for sent in sentences:
for i, w in enumerate(sent):
for j in range(max(0, i - window), i):
c = sent[j]
weight = 1.0 / (i - j)
counts[(w, c)] += weight
counts[(c, w)] += weight
return counts
def f(x, x_max=10.0, alpha=0.75):
return (x / x_max) ** alpha if x < x_max else 1.0
sentences = [
["the", "cat", "sits", "on", "the", "mat"],
["the", "dog", "sits", "on", "the", "rug"],
["the", "cat", "chases", "the", "mouse"],
]
X = cooccurrence(sentences, window=2)
vocab = sorted({w for s in sentences for w in s})
idx = {w: n for n, w in enumerate(vocab)}
entries = [(idx[a], idx[b], x) for (a, b), x in X.items()]
rng = np.random.default_rng(1)
dim, V = 10, len(vocab)
W = rng.normal(scale=0.1, size=(V, dim))
Wt = rng.normal(scale=0.1, size=(V, dim))
b = np.zeros(V)
bt = np.zeros(V)
def loss():
total = 0.0
for i, j, x in entries:
diff = W[i] @ Wt[j] + b[i] + bt[j] - np.log(x)
total += f(x) * diff ** 2
return total
print("initial loss:", round(loss(), 4))
lr = 0.1
for epoch in range(300):
for n in rng.permutation(len(entries)):
i, j, x = entries[n]
diff = W[i] @ Wt[j] + b[i] + bt[j] - np.log(x)
g = f(x) * diff
gw, gwt = g * Wt[j], g * W[i]
W[i] -= lr * gw
Wt[j] -= lr * gwt
b[i] -= lr * g
bt[j] -= lr * g
print("final loss:", round(loss(), 4))
embeddings = W + Wt
print(embeddings.shape)Both gw and gwt are computed before either vector changes, so the two updates use the same old values. The factor 2 from differentiating the square is folded into the learning rate. The final loss should be well below the initial one.
Details that matter
- Sum the two vector sets. The table is symmetric, so
WandW̃play interchangeable roles and differ only through random initialization. Their sum (W + W̃) is the standard output. It reduces noise and usually scores slightly better than either set alone. - Distance weighting changes the counts. GloVe adds
1/dper pair at distanced, so counts are not integers. A pair just counted once at distance 2 hasX = 0.5. This is whyfis applied to real-valued counts. - The vocabulary cutoff is part of the model. The GloVe tool takes a minimum count and drops rarer words before building the table. Changing it changes the table and the results.
- The log is of counts, not of probabilities. Because
log X_iwas absorbed into the bias, the target islog X_ij. Usinglog P_ijas the target and keeping the biases double-counts the correction. - Memory is the real cost. The table is sparse, but for a large vocabulary it can still hold billions of entries. The released GloVe tool stores it on disk and shuffles it between epochs.
Reading the objective critically
The derivation is a motivation. The log-bilinear form is a modeling choice that the ratio argument makes plausible, but the argument is not a proof. Levy and Goldberg showed that skip-gram with negative sampling implicitly factorizes a shifted pointwise-mutual-information matrix. The two methods are closer than their training loops suggest. The next chapter compares them directly.
Exercise
A word pair appears with weighted count X = 250 in a corpus, and another pair has X = 25. Using x_max = 100 and α = 0.75, compute f for each pair (to 3 decimals). Then state what the weight does for the pair with X = 250 compared with a plain least-squares fit.
Show answer
For X = 250, f = 1 because 250 ≥ x_max. For X = 25, f = (25/100)^0.75 = 0.25^0.75 ≈ 0.354. The cap means the pair with X = 250 contributes its squared error at full weight, but no more than any pair at or above 100. Without the cap, an unweighted fit would let very frequent pairs dominate the loss and the vectors would mostly encode stop-word statistics.
Exercise
Why does the GloVe loss skip cells where X_ij = 0, and what would go wrong if you included them with the target log(0)?
Show answer
log(0) is negative infinity, so the squared error is infinite and gradients are undefined. Skipping zeros is consistent with f(0) = 0, and it also keeps training cost proportional to the number of nonzero cells instead of V².