Course contents 09 / 28

09 / 28 · Distributed Representations

GloVe: embeddings from global co-occurrence counts

Fit weighted nonzero log counts with vectors and biases, derive the role of probability ratios, and verify an original full-batch optimization experiment.

Prerequisites

Word2Vec · Word embeddings

On this page 8

The same word pair can appear thousands of times while a context-prediction model walks through a corpus. We can count those repetitions once and work with their aggregate evidence. The remaining question is what a small pair of vector tables should reproduce: raw counts, conditional probabilities or a transformation that makes differences between context patterns easier to express.

Baseline: factorize the count matrix#

Let XijX_{ij} count how often word jj occurs in the chosen context of word ii. A context rule must specify distance, direction, boundary handling and any distance weights. A symmetric window gives a symmetric count matrix when each directed pair is weighted consistently; a directional context need not.

A low-rank model can fit entries with dot products. Direct squared error on raw counts, however, gives a large absolute error more influence than a small one. A prediction of ten instead of twenty and a prediction of one thousand instead of two thousand have the same relative error but very different squared errors. Transforming counts changes this preference; it is part of the model rather than harmless preprocessing.

The logarithm compresses scale and turns a ratio into a difference. It is undefined at zero. Replacing it with log(1 + count) and fitting every matrix entry gives one possible model, but that also makes every unobserved pair a numerical reconstruction target. GloVe instead fits selected nonzero log counts with a weighting function. These choices yield different losses and gradients.

Ratios carry the meaning#

Define the total count XiX_i of contexts for word ii and its empirical conditional distribution:

Xi=∑jXij,P(j∣i)=XijXi.\begin{aligned} X_i&=\sum_j X_{ij},\\ P(j\mid i)&=\frac{X_{ij}}{X_i}. \end{aligned}

For positive entries, a ratio compares how much of two words’ context mass is assigned to the same context. Using the invented equipment corpus, lamp has six contexts and microphone has four. For charge, their probabilities are 4/6 and 2/4; for inspect, they are 2/6 and 1/4. Both ratios equal 4/3.

This identifies a shared relative pattern on those two contexts. The adjust context differs: its count with lamp is zero and with microphone is one. The corresponding ratio is zero and its logarithm is not finite. We cannot simply insert every empirical ratio into a finite vector equation, and we should not interpret one small corpus as a description of the words’ universal meanings.

For positive probabilities, taking logarithms gives

ln⁡P(k∣i)P(k∣j)=ln⁡P(k∣i)−ln⁡P(k∣j).\ln\frac{P(k\mid i)}{P(k\mid j)} =\ln P(k\mid i)-\ln P(k\mid j).

A difference is compatible with linear operations on vectors. This motivates a log-bilinear model; it does not prove that linguistic relations are exactly linear or that a particular low-dimensional fit exists with zero error.

From ratios to a model#

Use target vectors uiu_i, context vectors wjw_j and separate scalar biases bib_i, cjc_j. GloVe fits

ui⊤wj+bi+cj≈ln⁡Xij.u_i^\top w_j+b_i+c_j\approx\ln X_{ij}.

The two vectors have dimension dd. Biases account for row- and column-related offsets without forcing every frequency effect into the vector directions. They are learned parameters, not automatically equal to logarithms of observed marginal counts.

Subtracting two fitted equations with the same context cancels its context bias. To compare conditional probabilities, also subtract the row-normalization terms:

ln⁡P(k∣i)P(k∣j)≈(ui−uj)⊤wk+bi−bj−ln⁡Xi+ln⁡Xj.\begin{aligned} \ln\frac{P(k\mid i)}{P(k\mid j)} &\approx(u_i-u_j)^\top w_k\\ &\quad+b_i-b_j-\ln X_i+\ln X_j. \end{aligned}

This makes the assumptions visible. A vector difference is only part of the expression; the word biases and marginal totals also matter. A diagram of vector offsets alone cannot establish exact probability ratios. Moreover, low-dimensional fitting only approximates the nonzero log-count equations.

The target/context distinction is a training role. A downstream representation can use one table or a documented combination of the two. The paper discusses combining vectors, but that is a separate export choice from the loss itself. Neither a sum nor a single table is guaranteed optimal for every application.

Weighted least squares#

Let S\mathcal S contain the nonzero count entries and let MM be their number. For a clear gradient convention, our executed example uses

rij=ui⊤wj+bi+cj−ln⁡Xij,J=12M∑(i,j)∈Sf(Xij)rij2.\begin{aligned} r_{ij}&=u_i^\top w_j+b_i+c_j-\ln X_{ij},\\ J&=\frac1{2M}\sum_{(i,j)\in\mathcal S}f(X_{ij})r_{ij}^2. \end{aligned}

The factor of one half and the mean over entries only rescale the paper’s sum objective; they affect the effective learning rate, not its unconstrained minimizers. The weight is

f(x)=min⁡((x/xmax⁡)α,1).f(x)=\min\left((x/x_{\max})^\alpha,1\right).

for positive counts. We skip zero entries before taking any logarithm. Multiplying an already computed negative infinity by zero would not be a valid numerical implementation of that rule.

The weight grows from small values for rare pairs and saturates for frequent ones. It reduces the influence of a noisy isolated count without letting the largest counts acquire arbitrarily large weights. The threshold and exponent remain hyperparameters. Our small case deliberately uses a count threshold of four, suitable for its visible counts; it does not inherit a large-corpus experiment’s settings or results.

For one pair, define gij=f(Xij)rij/Mg_{ij}=f(X_{ij})r_{ij}/M. Its contributions are

∇uiJ+=gijwj,∇wjJ+=gijui,∇biJ+=gij,∇cjJ+=gij.\begin{aligned} \nabla_{u_i}J&\mathrel{+}=g_{ij}w_j,\\ \nabla_{w_j}J&\mathrel{+}=g_{ij}u_i,\\ \nabla_{b_i}J&\mathrel{+}=g_{ij},\\ \nabla_{c_j}J&\mathrel{+}=g_{ij}. \end{aligned}

The accumulation symbol matters: each word participates in several pairs. A full-batch step collects all contributions using the old parameters and then updates once. Stochastic or adaptive implementations have different update schedules; reproducing their trajectories requires those details too.

A run on the invented counts#

The sixteen two-word messages produce 32 directed context events. In vocabulary order lamp, tripod, microphone, charge, inspect, adjust, the complete symmetric matrix has fourteen nonzero entries. Its upper-right block is small enough to inspect directly:

Targetchargeinspectadjust
lamp420
tripod033
microphone211

The lower-left block is its transpose; the other blocks are zero because each message contains one equipment word and one action. We keep those boundaries rather than connecting the end of one message to the beginning of another.

Set dimension two, threshold four and exponent 3/4. The observed-count weights are:

CountWeight
10.353553
20.594604
30.805927
41

There are 24 vector coordinates and twelve bias parameters. The script gives the vector coordinates a fixed small nonzero modular initialization and starts biases at zero. Nonzero vector initialization matters: if both tables were entirely zero, their bilinear gradients would initially be zero even though the biases could still change.

Eight hundred full-batch steps of size 0.3 produce the following saved mean losses:

StepWeighted loss
00.3364305701
1000.0012613751
4000.0000409102
8000.0000118566

This is a real standard-library optimization run on the newly specified counts. Every initial and final gradient coordinate was compared with centered finite differences. The script records all fitted parameters and predictions; for example:

PairTarget log countFitted score
lamp / charge1.3862941.391703
tripod / adjust1.0986121.094777
microphone / inspect00.007997

Although the count matrix is symmetric, independently parameterized tables need not produce exactly symmetric fitted scores at a finite optimization step. Both directions are included in the loss. Their small remaining differences are optimization residuals, not new observations.

There are more free parameters than nonzero targets in this deliberately tiny case. Many parameter settings can explain the counts, and the objective does not directly penalize predictions at missing entries. A low training loss therefore provides no evidence of stable semantic neighborhoods or generalization. It verifies the implementation and illustrates which quantities the model tries to fit.

GloVe and skip-gram#

Both methods use word–context observations and two sets of vectors, but their losses differ. Full-softmax skip-gram normalizes context scores within each input row and fits observed conditional frequencies. The negative-sampling version compares positive counts with expected noise counts. Its isolated optimum depends on the noise distribution and number of negatives, as derived previously.

GloVe uses a weighted squared residual against a nonzero log count, with biases and no row-wise softmax. It does not sample negative pairs in this loss. Adding zero-count reconstruction penalties would change the objective. Conversely, replacing a logistic term with a squared residual is more than collecting the same pairs into a matrix.

Loss numbers across these methods are on different scales and cannot decide which embeddings are better. A comparison needs the same downstream task, data boundary, vocabulary policy and evaluation protocol. The two actual runs in our fixture are mechanism demonstrations, not competing benchmark measurements.

What changed#

The corpus is summarized by a reusable count matrix, and repeated pair evidence is represented by its count. Logarithms express relative scale more naturally than raw squared counts, while the weighting function controls the influence of rare and frequent nonzero entries. The cost of constructing and storing co-occurrences now becomes an explicit part of the pipeline.

Limitations#

A broad window and large vocabulary can create many distinct pairs even when the matrix is stored sparsely. Counting is still dependent on tokenization, domain, direction and boundaries. Rebuilding the corpus or changing the vocabulary changes the statistical object being fitted.

Zeros receive no direct reconstruction constraint in this objective. Rare words have few reliable contexts. A static row merges multiple meanings, and unseen words lack dedicated learned rows. Training remains nonconvex and representation coordinates are not uniquely identified. An orthogonal rotation of both vector tables preserves their dot products, and compensating bias shifts can leave scores unchanged too.

A useful deployment requires an evaluation outside these training counts. Check rare-word coverage, domain shifts and errors in the actual task. Inspecting a few neighbors may reveal a problem, but it cannot by itself establish a general quality claim.

What you should remember#

GloVe fits weighted nonzero log counts with two vector tables and biases. Conditional ratios motivate differences, with normalization and bias terms retained. Zero counts are skipped before logarithms. Weighting changes the influence of observations. A small reconstruction loss is training evidence, not semantic validation.

Reproducible example#

The glove section of the original executable fixture rebuilds all counts, checks gradients and runs the stated optimizer. Saved results include all 36 final parameters and fourteen fitted scores. They were produced with Python 3.9.7; another runtime may differ in final floating-point digits. No original GloVe implementation, external corpus or pretrained weights are bundled.

Code#

The implementation separates count construction, loss/gradient calculation and parameter updates. glove_loss_gradient skips missing entries, computes one residual per present pair and accumulates derivatives into both tables and bias arrays. glove_case supplies the explicit initialization and learning schedule. This structure makes the mathematical contract independently checkable without a training framework or data download.

Next#

A dedicated word row still fails for a new spelling. FastText shares input parameters through character sequences so an unseen word can assemble a representation from parts, while making the resulting collisions and limitations visible.

References#

  • Jeffrey Pennington, Richard Socher, Christopher D. Manning. GloVe: Global Vectors for Word Representation, 2014, section 3, equations 7–9 and section 3.1. Scientific reference for log-bilinear modeling, weighting and comparison with context prediction; the source’s illustrative corpus statistics, diagrams and benchmark outputs are not reused.
  • The Board of Trustees of the Leland Stanford Junior University; GloVe contributors. GloVe implementation, revision 52f7dbc, Apache-2.0. The weighted residual and bias conventions were checked. Our standard-library full-batch optimizer is independently implemented and has a different normalization and update schedule.