Algorithm Search⌘K

Modelcore

Skip-gram model

Also called word2vec skip-gram.

A log-linear model that predicts each word in a window around a word from that word's vector. Its learned input vectors are word embeddings.

The machine

The skip-gram model is a conditional model of a context word given a center word. It has these parts.

  • Vocabulary. A finite set VV of word types, fixed before training. Words outside VV are dropped or mapped to one unknown symbol.
  • Parameters. Two tables of real vectors of dimension dd: an input vector v⃗w∈Rd\vec v_w \in \mathbb{R}^d and an output vector u⃗w∈Rd\vec u_w \in \mathbb{R}^d for each w∈Vw \in V. As matrices they are WinW_{\text{in}} and WoutW_{\text{out}}, each of shape ∣V∣×d|V| \times d, so the model has 2∣V∣d2|V|d parameters.
  • Conditional distribution. For a center word ww and a context word cc, the model is a softmax over the vocabulary of the dot products:
P(c∣w)=exp⁡(u⃗c⋅v⃗w)∑j∈Vexp⁡(u⃗j⋅v⃗w).P(c \mid w) = \frac{\exp(\vec u_c \cdot \vec v_w)}{\sum_{j \in V} \exp(\vec u_j \cdot \vec v_w)}.

There is no hidden nonlinearity: the score of a pair is bilinear in the two vectors, so the model is log-linear in each table.

  • Training pairs. A corpus is a sequence of tokens w1,…,wNw_1, \ldots, w_N (in practice a list of sentences, and windows do not cross a sentence end). For each position tt, the training draws a radius RR uniformly from {1,…,C}\{1, \ldots, C\}, where CC is the maximum window, and emits the pairs (wt,wt+j)(w_t, w_{t+j}) for 1≤∣j∣≤R1 \le |j| \le R. A context word at distance δ\delta is therefore used with probability (C−δ+1)/C(C - \delta + 1)/C. Mikolov et al. describe this as giving less weight to distant words by sampling them less often.
  • Objective. Maximize the sum of log⁡P(wt+j∣wt)\log P(w_{t+j} \mid w_t) over the emitted pairs, by stochastic gradient ascent. After training, the rows of WinW_{\text{in}} are the word embedding; the output table is usually discarded.

The standing assumptions are a closed vocabulary, a bag of context words (the position jj inside the window does not enter P(c∣w)P(c \mid w)), and independence of the pairs in the objective.

The loss of one pair, and the way the pairs are made, as the code computes them:

  1. SKIP-GRAM-LOSS(w_1..w_N, C, W_in, W_out)
  2. 1for t ← 1 to N do
  3. 2R ← a uniform draw from {1, ..., C}
  4. 3for each j with 1 ≤ |j| ≤ R and 1 ≤ t + j ≤ N do emit (w_t, w_{t+j})
  5. 4for each emitted pair (w, c) do h ← v_w ▷ the row of W_in
  6. 5s_x ← u_x · h for every x in V ▷ |V| dot products
  7. 6loss ← loss - (s_c - log Σ_x exp(s_x)) ▷ -log P(c | w)

What it counts

The model assigns the probability P(c∣w)P(c \mid w) above to each context word, and the training loss is the cross-entropy −∑log⁡P(c∣w)-\sum \log P(c \mid w) over the emitted pairs. The gradient for one pair (w,c)(w, c) is

∂∂v⃗w(−log⁡P(c∣w))=∑x∈VP(x∣w) u⃗x−u⃗c,∂∂u⃗x(−log⁡P(c∣w))=(P(x∣w)−[x=c]) v⃗w.\frac{\partial}{\partial \vec v_w}\big(-\log P(c \mid w)\big) = \sum_{x \in V} P(x \mid w)\,\vec u_x - \vec u_c, \qquad \frac{\partial}{\partial \vec u_x}\big(-\log P(c \mid w)\big) = \big(P(x \mid w) - [x = c]\big)\,\vec v_w.

Example. Take V={the,cat,sat,on,mat}V = \{\text{the}, \text{cat}, \text{sat}, \text{on}, \text{mat}\}, d=2d = 2, v⃗cat=(1,0)\vec v_{\text{cat}} = (1, 0) and the output vectors u⃗the=u⃗cat=(0,0)\vec u_{\text{the}} = \vec u_{\text{cat}} = (0, 0), u⃗sat=(1,1)\vec u_{\text{sat}} = (1, 1), u⃗on=(0.5,0)\vec u_{\text{on}} = (0.5, 0), u⃗mat=(−1,0)\vec u_{\text{mat}} = (-1, 0). The scores are (0,0,1,0.5,−1)(0, 0, 1, 0.5, -1), and the softmax gives

P(⋅∣cat)=(0.1485,0.1485,0.4036,0.2448,0.0546).P(\cdot \mid \text{cat}) = (0.1485, 0.1485, 0.4036, 0.2448, 0.0546).

The loss of the pair (cat, sat) is −log⁡0.4036=0.9073-\log 0.4036 = 0.9073 nats. Its gradient with respect to v⃗cat\vec v_{\text{cat}} is 0.4036(1,1)+0.2448(0.5,0)+0.0546(−1,0)−(1,1)=(−0.5286,−0.5964)0.4036 (1, 1) + 0.2448 (0.5, 0) + 0.0546 (-1, 0) - (1, 1) = (-0.5286, -0.5964), so a gradient step moves v⃗cat\vec v_{\text{cat}} toward u⃗sat\vec u_{\text{sat}}.

Cost of one evaluation. With the full softmax, one pair costs ∣V∣|V| dot products of length dd, that is O(∣V∣d)O(|V| d) time, for the loss and for the gradient. Each position has on average 2⋅1C∑δ=1C(C−δ+1)=C+12 \cdot \frac{1}{C}\sum_{\delta=1}^{C}(C - \delta + 1) = C + 1 pairs, so a pass over NN tokens costs O(NC∣V∣d)O(N C |V| d). This is too slow for a large vocabulary, and the model is trained with one of two approximations:

  • hierarchical softmax, which replaces the ∣V∣|V| scores by about log⁡2∣V∣\log_2 |V| binary decisions, O(dlog⁡∣V∣)O(d \log |V|) per pair;
  • negative sampling, which replaces the softmax by k+1k + 1 logistic terms, O((k+1)d)O((k + 1) d) per pair, and no longer defines a normalized P(c∣w)P(c \mid w).

Mikolov et al. give the training complexity per token as Q=C×(D+D×log⁡2V)Q = C \times (D + D \times \log_2 V) (their equation 5, with D=dD = d and V=∣V∣V = |V|), which counts one input vector and a hierarchical softmax for each of about CC context words.

Relation to other models

  • Continuous bag-of-words reverses the direction. It predicts the center word from the mean of the context vectors. It makes one prediction per position instead of about CC, so it trains faster.
  • Neural probabilistic language model. Bengio et al. 2003 predict the next word from the concatenated vectors of the previous words through a nonlinear hidden layer. The skip-gram model removes the hidden layer and the word order, and predicts in both directions. It is not a language model: it gives no probability to a sentence.
  • Softmax regression. For a fixed input vector v⃗w\vec v_w, P(c∣w)P(c \mid w) is a multinomial logistic regression whose weight rows are the output vectors. The model trains the input and the weights together.
  • Count methods. With negative sampling and a large enough dimension, the optimum factorizes a shifted PMI matrix (SGNS factorization theorem). GloVe fits the log counts directly, and a truncated SVD of a PPMI matrix is the classic count analogue.
  • Extensions. Subword information embeddings replace v⃗w\vec v_w by a sum of character n-gram vectors. DeepWalk and node2vec apply the skip-gram model to random walks on a graph. The paragraph vector adds a document vector to the input.

Known results in the model

The free-score optimum is the conditional frequency. Let #(w,c)\#(w, c) be the number of emitted pairs and #(w)=∑c#(w,c)\#(w) = \sum_c \#(w, c). If each row of scores sw,⋅s_{w, \cdot} could be set freely, the objective ∑w,c#(w,c)log⁡P(c∣w)\sum_{w, c} \#(w, c) \log P(c \mid w) is maximized when P(c∣w)=#(w,c)/#(w)P(c \mid w) = \#(w, c)/\#(w) for every word with #(w)>0\#(w) > 0.

Proof. The objective splits over ww. For a fixed ww, any distribution qq on VV satisfies ∑c#(w,c)log⁡q(c)=#(w)∑cp^(c)log⁡q(c)\sum_c \#(w, c) \log q(c) = \#(w) \sum_c \hat p(c) \log q(c) with p^(c)=#(w,c)/#(w)\hat p(c) = \#(w, c)/\#(w). By Gibbs' inequality, ∑cp^(c)log⁡q(c)≤∑cp^(c)log⁡p^(c)\sum_c \hat p(c) \log q(c) \le \sum_c \hat p(c) \log \hat p(c), with equality only at q=p^q = \hat p. Every distribution with full support is a softmax of some scores, and p^\hat p is approached as the scores of unseen pairs go to −∞-\infty. ■\blacksquare

So the scores are determined only up to a constant per row, swc=log⁡p^(c)+aws_{wc} = \log \hat p(c) + a_w. With a finite dd, the matrix WinWout⊤W_{\text{in}} W_{\text{out}}^\top has rank at most dd, and the trained model is a low-rank compromise, which is what makes similar words share vectors.

The dynamic window is a weighting. The expected number of times the pair (wt,wt+δ)(w_t, w_{t+\delta}) is used is (C−δ+1)/C(C - \delta + 1)/C: 1 for δ=1\delta = 1 and 1/C1/C for δ=C\delta = C. With C=5C = 5 the weights are 1,0.8,0.6,0.4,0.21, 0.8, 0.6, 0.4, 0.2. GloVe uses the weight 1/δ1/\delta for the same purpose.

Cost. The three training objectives cost O(∣V∣d)O(|V| d) (full softmax), O(dlog⁡∣V∣)O(d \log |V|) (balanced hierarchical softmax; for a Huffman tree, the expected path length is within one bit of the entropy of the word distribution) and O((k+1)d)O((k + 1) d) (negative sampling with kk noise words) per pair. The memory is 2∣V∣d2|V|d numbers for the two tables.

Measurements. These are measurements, not guarantees. On the analogy test set of Mikolov et al. (8869 semantic and 10675 syntactic questions), Pennington, Socher and Manning report for 300-dimensional vectors trained on 6 billion tokens with the word2vec tool an accuracy of 73.0 percent (semantic), 66.0 percent (syntactic) and 69.1 percent (total) for skip-gram, against 63.6, 67.4 and 65.7 percent for CBOW (their Table 2). The result depends on the corpus, the window, the number of epochs and the evaluation method of word analogy.

Code

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.

skip_gram_model.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/skip-gram-model/. The authors are listed in prov/PV50G4.jsonl.

"""The skip-gram model of Mikolov, Chen, Corrado and Dean 2013, with a full softmax.

Each word w has an input vector v_w (a row of vin) and an output vector u_w
(a row of uout). The model gives P(c | w) = exp(u_c . v_w) / sum_j exp(u_j . v_w).
The training pairs come from a window of random radius R, uniform in 1 to C,
drawn again at each position. The code takes the corpus as a list of lists of
word ids. It is the full softmax form; negative sampling and hierarchical
softmax have their own pages.
"""

import math
import random
from typing import Sequence


def log_softmax(scores: Sequence[float]) -> list[float]:
    m = max(scores)
    z = m + math.log(sum(math.exp(s - m) for s in scores))
    return [s - z for s in scores]


def training_pairs(corpus: Sequence[Sequence[int]], c_max: int, rng: random.Random) -> list[tuple[int, int]]:
    """(center, context) pairs with a window radius R drawn uniformly from 1 to C."""
    pairs = []
    for sent in corpus:
        n = len(sent)
        for t in range(n):  # @line L1
            r = rng.randint(1, c_max)  # @line L2
            for j in range(max(0, t - r), min(n, t + r + 1)):  # @line L3
                if j != t:
                    pairs.append((sent[t], sent[j]))
    return pairs


def inclusion_probability(distance: int, c_max: int) -> float:
    """P(a context word at the given distance is used) = (C - distance + 1) / C."""
    return max(0, c_max - distance + 1) / c_max


def probabilities(vin, uout, w: int) -> list[float]:
    """P(. | w) over the whole vocabulary."""
    h = vin[w]
    return [math.exp(x) for x in log_softmax([sum(a * b for a, b in zip(u, h)) for u in uout])]


def pair_loss(vin, uout, w: int, c: int) -> float:
    """-log P(c | w)."""
    h = vin[w]  # @line L4
    scores = [sum(a * b for a, b in zip(u, h)) for u in uout]  # @line L5
    return -log_softmax(scores)[c]  # @line L6


def pair_gradient(vin, uout, w: int, c: int):
    """Gradient of pair_loss: (gradient of v_w, gradient of every u_j)."""
    p = probabilities(vin, uout, w)
    h = vin[w]
    d = len(h)
    gv = [0.0] * d
    gu = []
    for j, u in enumerate(uout):
        e = p[j] - (1.0 if j == c else 0.0)
        gu.append([e * a for a in h])
        for k in range(d):
            gv[k] += e * u[k]
    return gv, gu


def corpus_loss(vin, uout, pairs) -> float:
    return sum(pair_loss(vin, uout, w, c) for w, c in pairs)


def train(corpus, vocab_size: int, d: int = 8, c_max: int = 2, epochs: int = 5,
          lr: float = 0.1, seed: int = 0):
    """Plain SGD over the pairs. Returns (vin, uout)."""
    rng = random.Random(seed)
    vin = [[(rng.random() - 0.5) / d for _ in range(d)] for _ in range(vocab_size)]
    uout = [[0.0] * d for _ in range(vocab_size)]
    for _ in range(epochs):
        for w, c in training_pairs(corpus, c_max, rng):
            gv, gu = pair_gradient(vin, uout, w, c)
            for j in range(vocab_size):
                for k in range(d):
                    uout[j][k] -= lr * gu[j][k]
            for k in range(d):
                vin[w][k] -= lr * gv[k]
    return vin, uout


def free_score_optimum(pairs, vocab_size: int) -> dict[int, list[float]]:
    """With a free score for every (w, c), the loss is least at P(c | w) = n(w, c) / n(w)."""
    counts: dict[int, list[int]] = {}
    for w, c in pairs:
        counts.setdefault(w, [0] * vocab_size)[c] += 1
    return {w: [x / sum(row) for x in row] for w, row in counts.items()}
test_skip_gram_model.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/skip-gram-model/. The authors are listed in prov/PV50G4.jsonl.

import math
import random

from skip_gram_model import (
    corpus_loss,
    free_score_optimum,
    inclusion_probability,
    pair_gradient,
    pair_loss,
    probabilities,
    train,
    training_pairs,
)


def rand_matrix(rng, n, d, scale=0.5):
    return [[rng.uniform(-scale, scale) for _ in range(d)] for _ in range(n)]


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_probabilities_sum_to_one():
    rng = random.Random(1)
    vin, uout = rand_matrix(rng, 12, 5, 2.0), rand_matrix(rng, 12, 5, 2.0)
    for w in range(12):
        p = probabilities(vin, uout, w)
        assert abs(sum(p) - 1.0) < 1e-12 and min(p) > 0


def test_gradient_against_finite_differences():
    rng = random.Random(2)
    vin, uout = rand_matrix(rng, 7, 4), rand_matrix(rng, 7, 4)
    h = 1e-6
    for w, c in [(0, 3), (5, 5), (6, 1)]:
        gv, gu = pair_gradient(vin, uout, w, c)
        for mat, row, grad in [(vin, w, gv)] + [(uout, j, gu[j]) for j in range(7)]:
            for k in range(4):
                old = mat[row][k]
                mat[row][k] = old + h
                up = pair_loss(vin, uout, w, c)
                mat[row][k] = old - h
                down = pair_loss(vin, uout, w, c)
                mat[row][k] = old
                assert abs((up - down) / (2 * h) - grad[k]) < 1e-5


def test_window_pairs_and_inclusion_probability():
    rng = random.Random(3)
    pairs = training_pairs([[0, 1, 2, 3, 4]], 1, rng)
    assert pairs == [(0, 1), (1, 0), (1, 2), (2, 1), (2, 3), (3, 2), (3, 4), (4, 3)]
    c_max, trials = 3, 6000
    hits = {1: 0, 2: 0, 3: 0}
    for _ in range(trials):
        for w, c in training_pairs([[0, 1, 2, 3, 4, 5, 6]], c_max, rng):
            if w == 3 and c > 3:
                hits[c - 3] += 1
    for dist in (1, 2, 3):
        assert abs(hits[dist] / trials - inclusion_probability(dist, c_max)) < 0.02
    assert [inclusion_probability(k, 5) for k in range(1, 7)] == [1.0, 0.8, 0.6, 0.4, 0.2, 0.0]


def test_free_scores_optimum_is_the_conditional_frequency():
    pairs = [(0, 1)] * 3 + [(0, 2)] + [(1, 0)] * 2 + [(1, 2)] * 2
    best = free_score_optimum(pairs, 3)
    assert best[0] == [0.0, 0.75, 0.25] and best[1] == [0.5, 0.0, 0.5]

    def log_lik(q):
        return sum(math.log(q[w][c]) for w, c in pairs)

    rng = random.Random(4)
    top = log_lik(best)
    for _ in range(200):
        q = {}
        for w in best:
            raw = [rng.random() + 1e-9 for _ in range(3)]
            q[w] = [x / sum(raw) for x in raw]
        assert log_lik(q) <= top


def planted_corpus(seed=0, sentences=60, length=6):
    rng = random.Random(seed)
    groups = [(list(range(0, 4)), list(range(8, 11))), (list(range(4, 8)), list(range(11, 14)))]
    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 test_planted_clusters_come_apart():
    corpus, groups = planted_corpus(seed=5)
    rng = random.Random(5)
    vin, uout = train(corpus, 14, d=6, c_max=2, epochs=4, lr=0.1, seed=5)
    (a, _), (b, _) = groups
    inside = [cos(vin[u], vin[v]) for g in (a, b) for k, u in enumerate(g) for v in g[k + 1:]]
    across = [cos(vin[u], vin[v]) for u in a for v in b]
    assert min(inside) > max(across)
    pairs = training_pairs(corpus, 2, rng)
    start = corpus_loss([[0.0] * 6 for _ in range(14)], uout, pairs)
    assert corpus_loss(vin, uout, pairs) < 0.8 * start

References

  1. Mikolov, Chen, Corrado and Dean 2013, Section 3.2 (the continuous skip-gram model, the training complexity Q = C x (D + D x log2(V)) of equation 5, and the window radius R drawn from 1 to C, with C = 10 in the experiments), Figure 1, Section 4.1 (the analogy test set)
  2. Mikolov, Sutskever, Chen, Corrado and Dean 2013, the skip-gram objective as an average log probability over the window, the full softmax and its cost, hierarchical softmax, negative sampling and subsampling
  3. Goldberg and Levy 2014, the skip-gram objective written as a sum over the word and context pairs of a corpus
  4. Pennington, Socher and Manning 2014, Table 2 (analogy accuracy of skip-gram and CBOW vectors trained by the authors with the word2vec tool on 6 billion tokens)

Where this leads

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW0 stub
  • the lead paragraph