Algorithmcore
GloVe
Also called global vectors for word representation.
Fit word and context vectors whose dot product plus biases matches the log co-occurrence count, by weighted least squares on nonzero counts.
- Time
- O(N K + T M d) worst
- Space
- O(M + V d) extra
- Where
- K = the window radius; M = the number of nonzero co-occurrence cells; N = the number of tokens in the corpus; T = the number of epochs; V = the vocabulary size, the number of types; d = the dimension of the vectors
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jeffrey Pennington, Richard Socher, Christopher D. Manning, 2014
GloVe fits a vector and a context vector to each word so that their dot product, plus a bias for each, is close to the logarithm of the number of times the two words occur near each other. It first counts the co-occurrences of the corpus into a sparse matrix , and then minimizes a weighted sum of squared errors over the nonzero cells of only, with a weight that grows with the count and stops at a cap. Pennington, Socher and Manning (2014) proposed it. It works on the global counts, like latent semantic analysis, and fits a log-bilinear model, like the skip-gram model. Its cost after the counting pass depends on the number of distinct pairs, not on the length of the corpus.
In plain words
First go through the text once and count, for every pair of words, how often they appear close to each other. Pairs that are very close count more than pairs that are far apart.
Then give each word two short lists of numbers and a single extra number for each list. For every pair that was seen at least once, combine the two lists of the two words into one score. The goal is that this score, plus the two extra numbers, matches the logarithm of the count.
The fit cares more about pairs seen many times, because their counts are reliable, but there is a limit so that very common pairs do not take over. Pairs never seen are skipped. The two lists of each word are added together at the end to give its vector.
The problem
The input is a corpus of tokens over a vocabulary , a window radius , a dimension and the constants and . The co-occurrence matrix has the entries
counted in both directions, so is symmetric. The output is a vector for each word, from parameters that minimize
Pennington et al. ask for three conditions on : with bounded as , non-decreasing, and not too large for large . They fix and , values chosen from their measurements. The cost is not convex in the parameters, and GloVe looks for a local minimum by stochastic descent.
The algorithm
GLOVE(corpus, K, d, T, η, x_max, α)- 1
X ← the co-occurrence counts, 1/r for each pair at distance r ≤ K, both directions - 2
W, W~ ← small uniform random values; b, b~ ← 0; every AdaGrad sum G ← 1 - 3
for epoch ← 1 to T do - 4
for each cell (i, j) with X_ij > 0, in random order do - 5
e ← w_i · w~_j + b_i + b~_j - log X_ij ▷ the residual - 6
g ← f(X_ij) e ▷ half the gradient factor - 7
w_i ← w_i - η g w~_j / sqrt(G); w~_j ← w~_j - η g w_i / sqrt(G); same for b_i and b~_j; then G ← G + (the gradient)^2 - 8
return W + W~ ▷ one vector per word
Line L1 is one pass over the corpus. For each token it looks back at the previous tokens and adds to both and , as the released counting tool does with its symmetric window. Line L2 starts the vectors near zero, with values in , and starts each AdaGrad sum at 1, as the released code does, so the first steps have the plain step size . Lines L4 to L7 are stochastic gradient descent with AdaGrad on one term of at a time. The term of cell has the gradient with respect to , and the code drops the factor 2 into the step size. Each coordinate has its own sum of squared gradients, so a parameter that has had large gradients takes smaller steps. Line L8 adds the two vector sets. Because is symmetric, and fit the same data and differ only by their random start; Pennington et al. report that the sum gives a small gain.
Example
Take the one-sentence corpus "the cat sat" with . The pairs are (the, cat) and (cat, sat) at distance 1 and (the, sat) at distance 2, so
| the | cat | sat | |
|---|---|---|---|
| the | 0 | 1 | 0.5 |
| cat | 1 | 0 | 1 |
| sat | 0.5 | 1 | 0 |
The diagonal cells and every zero cell are skipped by line L4, so there are six terms. With the weights are tiny, and , because the counts are far below the cap; for this toy, take , so and .
One step on the cell (sat, the), with , , , zero biases, and all AdaGrad sums at 1:
| quantity | line | value |
|---|---|---|
| L5 | 0.7031 | |
| L6 | 0.4181 | |
| L7 | (0.0937, 0.2021) | |
| L7 | (0.2979, -0.1042) | |
| and | L7 | -0.0209 each |
| new residual | L5 | 0.6582 |
The term goes from 0.2940 to 0.2576. Most of the gain comes from the two biases, which move the score toward . The AdaGrad sum of the first coordinate of is now .
On a planted corpus where five words occur only with one set of context words and five other words only with another set, a run with , , and 40 epochs gives a cosine between any two words of the same group that is higher than any cosine across the groups.
Correctness
GloVe is a heuristic optimizer: the claims are about what each line computes, not about a global minimum.
- Line L1 computes exactly as defined: every unordered pair of tokens at distance is visited once, from its later token, and adds to both cells.
- Lines L5 to L7 move each parameter against the exact gradient of one term of , scaled per coordinate by . A positive diagonal scaling of a gradient is still a descent direction, so for a small enough each step lowers that term.
- , and exactly when every cell with is fitted exactly. If the matrix of on the nonzero cells can be matched by a rank- product plus biases, such a point is a global minimum.
- For fixed context vectors and biases, is a convex quadratic in each (a weighted least squares problem), and the same holds with the roles swapped. This is why alternating least squares also applies.
The full proofs of the counting rule, the gradient and the descent property are in the proof file.
Proof: GloVe counts the co-occurrences exactly and each step is a descent step on the weighted least squares costfull
GloVe has no guarantee of a global minimum, because its cost is not convex. We prove the three facts that the algorithm relies on: line L1 computes the co-occurrence matrix of the definition, lines L5 to L7 use the exact gradient of one term of the cost, and each such step lowers that term for a small enough step size. We also prove the two facts about the minimum that the page states.
Notation. A sentence is a token sequence . For words and , the definition is
summed over the sentences. The cost is with , , and the residual .
Claim 1. Line L1 computes .
The loop visits every position and, for with , the position . So it visits each pair with exactly once, from its later position. For that pair it adds to the cell and to the cell . The cell therefore receives once for each such pair with and once for each such pair with . When , both additions go to the cell , which matches the two indicator terms of the definition that are both 1. The sum is the definition of . Since the definition is symmetric in and , so is .
Claim 2. Lines L5 to L7 use the gradient of .
Only is touched in a visit of cell . With and , the chain rule gives
and every other partial derivative of is zero. When , and are still different parameters, so the formulas hold unchanged. Line L6 sets , which is half of the common factor, and line L7 moves each of these parameters by times the matching vector, with all quantities taken at the point before the step. So the step is , where is the diagonal matrix of the values of the touched coordinates and is zero elsewhere.
Claim 3. For a small enough the step lowers .
If there is nothing to show. Otherwise, is a polynomial in the parameters, so it is differentiable, and by Taylor's theorem
The gradient is zero outside the touched coordinates, and is positive on them, so . For small enough, the negative term is larger than the remainder, and . The values of only grow during the run (line L7 adds squares), so stays bounded by its start value, which is the identity on the touched coordinates because starts at 1.
Claim 4. , with exactly at an exact fit.
Every term is with , so , and if and only if for every . So if some parameters fit every nonzero cell exactly, they are a global minimum, and every global minimum with value 0 is such a fit.
Claim 5. is a convex quadratic in each with the rest fixed.
Fix all parameters except . Then with . This is a weighted least squares cost in , with Hessian , which is positive semidefinite. So is convex in , and the same argument applies to and to the biases.
Complexity
Line L1 does updates per token, time with a hash table, and stores the nonzero cells. Each cell visit of lines L5 to L7 costs , so an epoch costs and the training . The memory is for and for the four parameter tables and the AdaGrad sums. is at most . Pennington et al. model the counts as a power law of the rank of the pair; with the exponent 1.25 that they measured on their corpora, grows like with the corpus size . This is a measurement on their corpora, not a bound.
Properties
- Randomized. The start and the order of the cells are random. With a fixed seed the run is repeatable.
- Counts first. After line L1 the corpus is no longer needed, and the cost of an epoch does not depend on .
- Only nonzero cells. The weight removes the zero cells from , which avoids and keeps the cost proportional to .
- Not normalized. The dot products fit log counts, not probabilities. The biases absorb the word frequencies.
- Symmetric. For a symmetric , swapping with and with maps solutions to solutions.
Variants and improvements
- Asymmetric windows. Counting only the left context gives a non-symmetric ; Pennington et al. report it as better for the syntactic analogies with small windows.
- The unweighted log baseline. Fitting on all cells with equal weights gives an SVD-like model that Pennington et al. use as a baseline. GloVe differs by the weight and by skipping the zeros.
- Count models. A truncated SVD of a PPMI matrix factorizes a similar matrix in closed form. Skip-gram with negative sampling has an optimum at the shifted PMI matrix (SGNS factorization theorem). GloVe's plays the role of the PMI, with the biases learned instead of fixed to the log marginals.
- Other optimizers. Plain SGD, Adam or alternating least squares minimize the same .
When to use it
Use GloVe when the corpus is large and you can afford the memory for the nonzero counts: each epoch costs , so many epochs are cheap compared with passes over the text. Use skip-gram with negative sampling when the counts do not fit in memory or the text arrives as a stream. Levy, Goldberg and Dagan (2015) found that, with the same hyperparameters and preprocessing, neither method is better on all tasks. For subword information or vectors for unseen words, use subword information embeddings.
Pitfalls
- Zero cells. Line L4 must loop over the nonzero cells only. Looping over all cells calls on line L5.
- The weight above the cap. Line L6 must use for . Using for all gives the most frequent pairs, such as those with "the", weights far above 1, and they then dominate the fit.
- AdaGrad sums at zero. If line L2 starts at 0 instead of 1, the first step divides by for any coordinate with a zero gradient so far. Start at a positive value, or add a small constant.
- Distance weight. Line L1 adds , not 1. Without the weight, distant pairs count as much as adjacent ones, which changes and the vectors.
- The factor 2. The code drops the factor 2 of the gradient into . A gradient check must compare with , not .
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/glove/. The authors are listed in prov/S7WPYE.jsonl.
"""GloVe (Pennington, Socher and Manning 2014) on a tiny corpus.
cooccurrence counts each pair of tokens at distance r <= window with the
weight 1 / r, in both directions, as the released cooccur tool does with its
symmetric option. The cost is
J = sum over X_ij > 0 of f(X_ij) (w_i . wt_j + b_i + bt_j - log X_ij)^2
with f(x) = (x / x_max)^alpha for x < x_max and 1 otherwise. train runs
AdaGrad over the nonzero cells in random order. Each step uses the gradient of
one term of J without its factor 2 (the factor goes into the step size), and
the AdaGrad sums start at 1, as in the released code. The word vectors are
w_i + wt_i.
"""
import math
import random
from typing import Sequence
Cooc = dict[tuple[int, int], float]
def build_vocab(corpus: Sequence[Sequence[str]]) -> dict[str, int]:
"""Word to index, by falling count and then by the word."""
counts: dict[str, int] = {}
for sent in corpus:
for w in sent:
counts[w] = counts.get(w, 0) + 1
order = sorted(counts, key=lambda w: (-counts[w], w))
return {w: i for i, w in enumerate(order)}
def cooccurrence(corpus: Sequence[Sequence[str]], vocab: dict[str, int], window: int = 10) -> Cooc:
"""X[i, j] = sum of 1 / r over the pairs of tokens i and j at distance r <= window."""
x: Cooc = {}
for sent in corpus:
ids = [vocab[w] for w in sent]
for p, i in enumerate(ids):
for r in range(1, window + 1):
if p - r < 0:
break
j = ids[p - r]
x[(i, j)] = x.get((i, j), 0.0) + 1.0 / r
x[(j, i)] = x.get((j, i), 0.0) + 1.0 / r
return x
def weight(x: float, x_max: float = 100.0, alpha: float = 0.75) -> float:
"""f(x) = (x / x_max)^alpha below x_max, else 1; f(0) = 0."""
return (x / x_max) ** alpha if x < x_max else 1.0
def init_params(n: int, d: int, seed: int = 0) -> dict[str, list]:
rng = random.Random(seed)
u = lambda: [(rng.random() - 0.5) / d for _ in range(d)] # noqa: E731
return {"w": [u() for _ in range(n)], "wt": [u() for _ in range(n)],
"b": [0.0] * n, "bt": [0.0] * n}
def residual(p: dict[str, list], i: int, j: int, xij: float) -> float:
return sum(a * c for a, c in zip(p["w"][i], p["wt"][j])) + p["b"][i] + p["bt"][j] - math.log(xij)
def cost(p: dict[str, list], x: Cooc, x_max: float = 100.0, alpha: float = 0.75) -> float:
"""The weighted least squares cost J over the nonzero cells."""
return sum(weight(v, x_max, alpha) * residual(p, i, j, v) ** 2 for (i, j), v in x.items())
def gradient(p: dict[str, list], x: Cooc, x_max: float = 100.0, alpha: float = 0.75) -> dict[str, list]:
"""The exact gradient of J with respect to every parameter."""
n, d = len(p["w"]), len(p["w"][0])
g = {"w": [[0.0] * d for _ in range(n)], "wt": [[0.0] * d for _ in range(n)],
"b": [0.0] * n, "bt": [0.0] * n}
for (i, j), v in x.items():
e = 2.0 * weight(v, x_max, alpha) * residual(p, i, j, v)
for k in range(d):
g["w"][i][k] += e * p["wt"][j][k]
g["wt"][j][k] += e * p["w"][i][k]
g["b"][i] += e
g["bt"][j] += e
return g
def train(x: Cooc, n: int, d: int, epochs: int = 50, lr: float = 0.05, seed: int = 0,
x_max: float = 100.0, alpha: float = 0.75) -> tuple[dict[str, list], list[float]]:
"""AdaGrad over the nonzero cells. Returns the parameters and the cost after each epoch."""
rng = random.Random(seed)
p = init_params(n, d, seed) # @line L2
gs = {"w": [[1.0] * d for _ in range(n)], "wt": [[1.0] * d for _ in range(n)],
"b": [1.0] * n, "bt": [1.0] * n}
cells = sorted(x)
history = []
for _ in range(epochs): # @line L3
rng.shuffle(cells)
for i, j in cells: # @line L4
v = x[(i, j)]
e = residual(p, i, j, v) # @line L5
fe = weight(v, x_max, alpha) * e # @line L6
wi, wj = p["w"][i], p["wt"][j]
for k in range(d): # @line L7
gi, gj = fe * wj[k], fe * wi[k]
wi[k] -= lr * gi / math.sqrt(gs["w"][i][k])
wj[k] -= lr * gj / math.sqrt(gs["wt"][j][k])
gs["w"][i][k] += gi * gi
gs["wt"][j][k] += gj * gj
p["b"][i] -= lr * fe / math.sqrt(gs["b"][i])
p["bt"][j] -= lr * fe / math.sqrt(gs["bt"][j])
gs["b"][i] += fe * fe
gs["bt"][j] += fe * fe
history.append(cost(p, x, x_max, alpha))
return p, history
def word_vectors(p: dict[str, list]) -> list[list[float]]:
"""The sum w_i + wt_i used as the final vector of word i."""
return [[a + b for a, b in zip(r, s)] for r, s in zip(p["w"], p["wt"])] # @line L8
def glove(corpus: Sequence[Sequence[str]], d: int, window: int = 10, epochs: int = 50,
lr: float = 0.05, seed: int = 0, x_max: float = 100.0, alpha: float = 0.75):
"""The whole method: counts, AdaGrad, and the summed vectors, keyed by word."""
vocab = build_vocab(corpus)
x = cooccurrence(corpus, vocab, window) # @line L1
p, _ = train(x, len(vocab), d, epochs, lr, seed, x_max, alpha)
vecs = word_vectors(p)
return {w: vecs[i] for w, i in vocab.items()}
test_glove.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/glove/. The authors are listed in prov/S7WPYE.jsonl.
import math
import random
from glove import (
build_vocab,
cooccurrence,
cost,
glove,
gradient,
init_params,
train,
weight,
)
def planted_corpus(seed=0, sentences=120, length=6):
"""Two clusters: words a* only meet contexts x*, words b* only meet contexts y*."""
rng = random.Random(seed)
groups = [([f"a{i}" for i in range(5)], [f"x{i}" for i in range(4)]),
([f"b{i}" for i in range(5)], [f"y{i}" for i in range(4)])]
corpus = []
for _ in range(sentences):
words, ctx = groups[rng.randrange(2)]
corpus.append([rng.choice(words) if k % 2 == 0 else rng.choice(ctx) for k in range(length)])
return corpus, groups
def cos(u, v):
return sum(a * b for a, b in zip(u, v)) / math.sqrt(sum(a * a for a in u) * sum(b * b for b in v))
def test_cooccurrence_against_all_position_pairs():
rng = random.Random(1)
words = "a b c d e".split()
corpus = [[rng.choice(words) for _ in range(rng.randint(1, 9))] for _ in range(15)]
vocab = build_vocab(corpus)
for window in (1, 2, 3, 10):
got = cooccurrence(corpus, vocab, window)
ref = {}
for sent in corpus:
for p in range(len(sent)):
for q in range(len(sent)):
if p != q and abs(p - q) <= window:
key = (vocab[sent[p]], vocab[sent[q]])
ref[key] = ref.get(key, 0.0) + 1.0 / abs(p - q)
assert set(got) == set(ref)
assert all(abs(got[k] - ref[k]) < 1e-12 for k in ref)
assert all(abs(got[(i, j)] - got[(j, i)]) < 1e-12 for i, j in got)
def test_hand_counts():
vocab = {"the": 0, "cat": 1, "sat": 2}
x = cooccurrence([["the", "cat", "sat"]], vocab, window=2)
assert x == {(1, 0): 1.0, (0, 1): 1.0, (2, 1): 1.0, (1, 2): 1.0, (2, 0): 0.5, (0, 2): 0.5}
def test_weight_function():
assert weight(0.0) == 0.0
assert weight(100.0) == 1.0 and weight(1000.0) == 1.0
assert abs(weight(50.0) - 0.5 ** 0.75) < 1e-15
assert abs(weight(1.0) - 0.0316227766) < 1e-9
xs = [0.5 * k for k in range(1, 400)]
assert all(weight(a) <= weight(b) for a, b in zip(xs, xs[1:]))
def test_gradient_against_finite_differences():
corpus, _ = planted_corpus(seed=2, sentences=10)
vocab = build_vocab(corpus)
x = cooccurrence(corpus, vocab, window=3)
rng = random.Random(3)
p = init_params(len(vocab), 4, seed=3)
for key in ("w", "wt"):
p[key] = [[rng.uniform(-0.5, 0.5) for _ in r] for r in p[key]]
p["b"] = [rng.uniform(-0.5, 0.5) for _ in p["b"]]
p["bt"] = [rng.uniform(-0.5, 0.5) for _ in p["bt"]]
g = gradient(p, x, x_max=4.0)
h = 1e-6
checks = [("w", i, k) for i in range(0, len(vocab), 3) for k in range(4)]
checks += [("wt", i, k) for i in range(1, len(vocab), 3) for k in range(4)]
checks += [("b", i, None) for i in range(len(vocab))] + [("bt", i, None) for i in range(len(vocab))]
for key, i, k in checks:
row = p[key] if k is None else p[key][i]
idx = i if k is None else k
old = row[idx]
row[idx] = old + h
up = cost(p, x, x_max=4.0)
row[idx] = old - h
down = cost(p, x, x_max=4.0)
row[idx] = old
num = (up - down) / (2 * h)
ana = g[key][i] if k is None else g[key][i][k]
assert abs(num - ana) < 1e-5 * max(1.0, abs(ana))
def test_training_lowers_cost():
corpus, _ = planted_corpus(seed=4, sentences=60)
vocab = build_vocab(corpus)
x = cooccurrence(corpus, vocab, window=2)
p0 = init_params(len(vocab), 8, seed=4)
start = cost(p0, x, x_max=10.0)
_, hist = train(x, len(vocab), 8, epochs=40, seed=4, x_max=10.0)
assert hist[-1] < 0.2 * start
assert hist[-1] <= hist[len(hist) // 2]
def test_planted_clusters_come_apart():
corpus, groups = planted_corpus(seed=5)
vec = glove(corpus, d=8, window=2, epochs=40, seed=5, x_max=10.0)
(a, x), (b, y) = groups
inside = [cos(vec[u], vec[v]) for g in (a, b) for k, u in enumerate(g) for v in g[k + 1:]]
across = [cos(vec[u], vec[v]) for u in a for v in b]
assert min(inside) > max(across)
assert sum(inside) / len(inside) - sum(across) / len(across) > 0.5
History
Pennington, Socher and Manning published GloVe at EMNLP 2014, with code and vectors trained on Wikipedia with Gigaword and on Common Crawl. They derived the model from the observation that ratios of co-occurrence probabilities, such as , separate related from unrelated words, and they showed that the skip-gram objective, grouped by word pairs, is a weighted sum over the same cells. The released vectors became a common input layer for neural models of language.
References
- Pennington, Socher and Manning 2014, Section 3 (equation 7, the log-bilinear relation with biases; equation 8, the weighted least squares cost; equation 9, the weighting function and its three conditions), Section 3.2 (the complexity, |X| = O(|C|^0.8) under a power law with exponent 1.25), Section 4.2 (x_max = 100, alpha = 3/4, AdaGrad with initial rate 0.05, the 1/d weight of distant pairs, and the sum W + W~)
- Duchi, Hazan and Singer 2011, the AdaGrad update with per-coordinate step sizes
- Levy, Goldberg and Dagan 2015, the comparison of GloVe, skip-gram with negative sampling, PPMI and SVD under the same hyperparameters
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag S7WPYE Edit this page History Report an error Markdown