Algorithm Search⌘K

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
Properties
randomizednot exactofflineiterative
Origin
Jeffrey Pennington, Richard Socher, Christopher D. Manning, 2014

GloVe fits a vector w⃗i\vec w_i and a context vector w⃗~j\tilde{\vec w}_j 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 XX, and then minimizes a weighted sum of squared errors over the nonzero cells of XX 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 NN tokens over a vocabulary VV, a window radius KK, a dimension dd and the constants xmax⁡x_{\max} and α\alpha. The co-occurrence matrix XX has the entries

Xij=∑token pairs (i,j) at distance r≤K1r,X_{ij} = \sum_{\text{token pairs } (i, j) \text{ at distance } r \le K} \frac{1}{r},

counted in both directions, so XX is symmetric. The output is a vector w⃗i+w⃗~i∈Rd\vec w_i + \tilde{\vec w}_i \in \mathbb{R}^d for each word, from parameters that minimize

J=∑i,j: Xij>0f(Xij)(w⃗i⋅w⃗~j+bi+b~j−log⁡Xij)2,f(x)={(x/xmax⁡)αx<xmax⁡,1otherwise.J = \sum_{i, j:\, X_{ij} > 0} f(X_{ij}) \big(\vec w_i \cdot \tilde{\vec w}_j + b_i + \tilde b_j - \log X_{ij}\big)^2, \qquad f(x) = \begin{cases} (x / x_{\max})^{\alpha} & x < x_{\max}, \\ 1 & \text{otherwise.} \end{cases}

Pennington et al. ask for three conditions on ff: f(0)=0f(0) = 0 with f(x)log⁡2xf(x)\log^2 x bounded as x→0x \to 0, ff non-decreasing, and ff not too large for large xx. They fix xmax⁡=100x_{\max} = 100 and α=3/4\alpha = 3/4, 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

  1. GLOVE(corpus, K, d, T, η, x_max, α)
  2. 1X ← the co-occurrence counts, 1/r for each pair at distance r ≤ K, both directions
  3. 2W, W~ ← small uniform random values; b, b~ ← 0; every AdaGrad sum G ← 1
  4. 3for epoch ← 1 to T do
  5. 4for each cell (i, j) with X_ij > 0, in random order do
  6. 5e ← w_i · w~_j + b_i + b~_j - log X_ij ▷ the residual
  7. 6g ← f(X_ij) e ▷ half the gradient factor
  8. 7w_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
  9. 8return W + W~ ▷ one vector per word

Line L1 is one pass over the corpus. For each token it looks back at the KK previous tokens and adds 1/r1/r to both XijX_{ij} and XjiX_{ji}, as the released counting tool does with its symmetric window. Line L2 starts the vectors near zero, with values in (−0.5/d,0.5/d)(-0.5/d, 0.5/d), and starts each AdaGrad sum at 1, as the released code does, so the first steps have the plain step size η\eta. Lines L4 to L7 are stochastic gradient descent with AdaGrad on one term of JJ at a time. The term of cell (i,j)(i, j) has the gradient 2f(Xij) e w⃗~j2 f(X_{ij})\, e\, \tilde{\vec w}_j with respect to w⃗i\vec w_i, and the code drops the factor 2 into the step size. Each coordinate has its own sum GG of squared gradients, so a parameter that has had large gradients takes smaller steps. Line L8 adds the two vector sets. Because XX is symmetric, WW and W~\tilde W 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 K=2K = 2. 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 xmax⁡=100x_{\max} = 100 the weights are tiny, f(1)=0.0316f(1) = 0.0316 and f(0.5)=0.0188f(0.5) = 0.0188, because the counts are far below the cap; for this toy, take xmax⁡=1x_{\max} = 1, so f(1)=1f(1) = 1 and f(0.5)=0.5946f(0.5) = 0.5946.

One step on the cell (sat, the), with d=2d = 2, w⃗sat=(0.1,0.2)\vec w_{\text{sat}} = (0.1, 0.2), w⃗~the=(0.3,−0.1)\tilde{\vec w}_{\text{the}} = (0.3, -0.1), zero biases, η=0.05\eta = 0.05 and all AdaGrad sums at 1:

quantity line value
e=0.01+0+0−log⁡0.5e = 0.01 + 0 + 0 - \log 0.5 L5 0.7031
g=0.5946×0.7031g = 0.5946 \times 0.7031 L6 0.4181
w⃗sat−0.05⋅0.4181⋅(0.3,−0.1)\vec w_{\text{sat}} - 0.05 \cdot 0.4181 \cdot (0.3, -0.1) L7 (0.0937, 0.2021)
w⃗~the−0.05⋅0.4181⋅(0.1,0.2)\tilde{\vec w}_{\text{the}} - 0.05 \cdot 0.4181 \cdot (0.1, 0.2) L7 (0.2979, -0.1042)
bsatb_{\text{sat}} and b~the\tilde b_{\text{the}} L7 -0.0209 each
new residual L5 0.6582

The term fe2f e^2 goes from 0.2940 to 0.2576. Most of the gain comes from the two biases, which move the score toward log⁡0.5=−0.6931\log 0.5 = -0.6931. The AdaGrad sum of the first coordinate of w⃗sat\vec w_{\text{sat}} is now 1+(0.4181×0.3)2=1.01571 + (0.4181 \times 0.3)^2 = 1.0157.

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 d=8d = 8, K=2K = 2, xmax⁡=10x_{\max} = 10 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 XX exactly as defined: every unordered pair of tokens at distance r≤Kr \le K is visited once, from its later token, and adds 1/r1/r to both cells.
  • Lines L5 to L7 move each parameter against the exact gradient of one term of JJ, scaled per coordinate by η/G>0\eta / \sqrt{G} > 0. A positive diagonal scaling of a gradient is still a descent direction, so for a small enough η\eta each step lowers that term.
  • J≥0J \ge 0, and J=0J = 0 exactly when every cell with Xij>0X_{ij} > 0 is fitted exactly. If the matrix of log⁡Xij\log X_{ij} on the nonzero cells can be matched by a rank-dd product plus biases, such a point is a global minimum.
  • For fixed context vectors and biases, JJ is a convex quadratic in each w⃗i\vec w_i (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 t1,…,tnt_1, \ldots, t_n. For words ii and jj, the definition is

Xij=∑1≤p<q≤n, q−p≤K1q−p([tq=i][tp=j]+[tp=i][tq=j]),X_{ij} = \sum_{1 \le p < q \le n,\ q - p \le K} \frac{1}{q - p}\Big([t_q = i][t_p = j] + [t_p = i][t_q = j]\Big),

summed over the sentences. The cost is J=∑(i,j)∈SJijJ = \sum_{(i, j) \in S} J_{ij} with S={(i,j):Xij>0}S = \{(i, j) : X_{ij} > 0\}, Jij=fij eij2J_{ij} = f_{ij}\, e_{ij}^2, fij=f(Xij)>0f_{ij} = f(X_{ij}) > 0 and the residual eij=w⃗i⋅w⃗~j+bi+b~j−log⁡Xije_{ij} = \vec w_i \cdot \tilde{\vec w}_j + b_i + \tilde b_j - \log X_{ij}.

Claim 1. Line L1 computes XX.

The loop visits every position qq and, for r=1,…,Kr = 1, \ldots, K with q−r≥1q - r \ge 1, the position p=q−rp = q - r. So it visits each pair p<qp < q with q−p≤Kq - p \le K exactly once, from its later position. For that pair it adds 1/(q−p)1/(q - p) to the cell (tq,tp)(t_q, t_p) and to the cell (tp,tq)(t_p, t_q). The cell (i,j)(i, j) therefore receives 1/(q−p)1/(q - p) once for each such pair with tq=i,tp=jt_q = i, t_p = j and once for each such pair with tp=i,tq=jt_p = i, t_q = j. When tp=tq=it_p = t_q = i, both additions go to the cell (i,i)(i, i), which matches the two indicator terms of the definition that are both 1. The sum is the definition of XijX_{ij}. Since the definition is symmetric in ii and jj, so is XX. □\square

Claim 2. Lines L5 to L7 use the gradient of JijJ_{ij}.

Only JijJ_{ij} is touched in a visit of cell (i,j)(i, j). With e=eije = e_{ij} and f=fijf = f_{ij}, the chain rule gives

∂Jij∂w⃗i=2fe w⃗~j,∂Jij∂w⃗~j=2fe w⃗i,∂Jij∂bi=∂Jij∂b~j=2fe,\frac{\partial J_{ij}}{\partial \vec w_i} = 2 f e\, \tilde{\vec w}_j, \quad \frac{\partial J_{ij}}{\partial \tilde{\vec w}_j} = 2 f e\, \vec w_i, \quad \frac{\partial J_{ij}}{\partial b_i} = \frac{\partial J_{ij}}{\partial \tilde b_j} = 2 f e,

and every other partial derivative of JijJ_{ij} is zero. When i=ji = j, w⃗i\vec w_i and w⃗~i\tilde{\vec w}_i are still different parameters, so the formulas hold unchanged. Line L6 sets g=feg = f e, which is half of the common factor, and line L7 moves each of these parameters by −ηg/G-\eta g / \sqrt{G} times the matching vector, with all quantities taken at the point before the step. So the step is Δ=−η2D∇Jij\Delta = -\frac{\eta}{2} D \nabla J_{ij}, where DD is the diagonal matrix of the values 1/G>01/\sqrt{G} > 0 of the touched coordinates and is zero elsewhere. □\square

Claim 3. For a small enough η\eta the step lowers JijJ_{ij}.

If ∇Jij=0\nabla J_{ij} = 0 there is nothing to show. Otherwise, JijJ_{ij} is a polynomial in the parameters, so it is differentiable, and by Taylor's theorem

Jij(θ+Δ)=Jij(θ)+∇Jij⋅Δ+o(η)=Jij(θ)−η2∇Jij⊤D∇Jij+o(η).J_{ij}(\theta + \Delta) = J_{ij}(\theta) + \nabla J_{ij} \cdot \Delta + o(\eta) = J_{ij}(\theta) - \frac{\eta}{2} \nabla J_{ij}^\top D \nabla J_{ij} + o(\eta).

The gradient is zero outside the touched coordinates, and DD is positive on them, so ∇Jij⊤D∇Jij>0\nabla J_{ij}^\top D \nabla J_{ij} > 0. For η\eta small enough, the negative term is larger than the remainder, and Jij(θ+Δ)<Jij(θ)J_{ij}(\theta + \Delta) < J_{ij}(\theta). The values of GG only grow during the run (line L7 adds squares), so DD stays bounded by its start value, which is the identity on the touched coordinates because GG starts at 1. □\square

Claim 4. J≥0J \ge 0, with J=0J = 0 exactly at an exact fit.

Every term is fijeij2f_{ij} e_{ij}^2 with fij>0f_{ij} > 0, so J≥0J \ge 0, and J=0J = 0 if and only if eij=0e_{ij} = 0 for every (i,j)∈S(i, j) \in S. 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. □\square

Claim 5. JJ is a convex quadratic in each w⃗i\vec w_i with the rest fixed.

Fix all parameters except w⃗i\vec w_i. Then J=∑j:(i,j)∈Sfij(w⃗~j⋅w⃗i−cj)2+constJ = \sum_{j : (i, j) \in S} f_{ij} (\tilde{\vec w}_j \cdot \vec w_i - c_j)^2 + \text{const} with cj=log⁡Xij−bi−b~jc_j = \log X_{ij} - b_i - \tilde b_j. This is a weighted least squares cost in w⃗i\vec w_i, with Hessian 2∑jfijw⃗~jw⃗~j⊤2 \sum_j f_{ij} \tilde{\vec w}_j \tilde{\vec w}_j^\top, which is positive semidefinite. So JJ is convex in w⃗i\vec w_i, and the same argument applies to w⃗~j\tilde{\vec w}_j and to the biases. ■\blacksquare

Complexity

Line L1 does KK updates per token, O(NK)O(NK) time with a hash table, and stores the MM nonzero cells. Each cell visit of lines L5 to L7 costs O(d)O(d), so an epoch costs O(Md)O(Md) and the training O(TMd)O(TMd). The memory is O(M)O(M) for XX and O(Vd)O(Vd) for the four parameter tables and the AdaGrad sums. MM is at most V2V^2. 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, MM grows like ∣C∣0.8|C|^{0.8} with the corpus size ∣C∣|C|. 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 NN.
  • Only nonzero cells. The weight f(0)=0f(0) = 0 removes the zero cells from JJ, which avoids log⁡0\log 0 and keeps the cost proportional to MM.
  • Not normalized. The dot products fit log counts, not probabilities. The biases absorb the word frequencies.
  • Symmetric. For a symmetric XX, swapping WW with W~\tilde W and bb with b~\tilde b maps solutions to solutions.

Variants and improvements

  • Asymmetric windows. Counting only the left context gives a non-symmetric XX; Pennington et al. report it as better for the syntactic analogies with small windows.
  • The unweighted log baseline. Fitting log⁡(1+Xij)\log(1 + X_{ij}) 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 log⁡Xij−bi−b~j\log X_{ij} - b_i - \tilde b_j 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 JJ.

When to use it

Use GloVe when the corpus is large and you can afford the memory for the nonzero counts: each epoch costs O(Md)O(Md), 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 log⁡0\log 0 on line L5.
  • The weight above the cap. Line L6 must use f(x)=1f(x) = 1 for x≥xmax⁡x \ge x_{\max}. Using (x/xmax⁡)α(x/x_{\max})^{\alpha} for all xx 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 GG at 0 instead of 1, the first step divides by 0\sqrt{0} for any coordinate with a zero gradient so far. Start at a positive value, or add a small constant.
  • Distance weight. Line L1 adds 1/r1/r, not 1. Without the weight, distant pairs count as much as adjacent ones, which changes XX and the vectors.
  • The factor 2. The code drops the factor 2 of the gradient into η\eta. A gradient check must compare with 2fe2 f e, not fef e.

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.

glove.pyI0RawGitHub
# 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 P(solid∣ice)/P(solid∣steam)P(\text{solid} \mid \text{ice}) / P(\text{solid} \mid \text{steam}), 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

  1. 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~)
  2. Duchi, Hazan and Singer 2011, the AdaGrad update with per-coordinate step sizes
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example