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 of word types, fixed before training. Words outside are dropped or mapped to one unknown symbol.
- Parameters. Two tables of real vectors of dimension : an input vector and an output vector for each . As matrices they are and , each of shape , so the model has parameters.
- Conditional distribution. For a center word and a context word , the model is a softmax over the vocabulary of the dot products:
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 (in practice a list of sentences, and windows do not cross a sentence end). For each position , the training draws a radius uniformly from , where is the maximum window, and emits the pairs for . A context word at distance is therefore used with probability . Mikolov et al. describe this as giving less weight to distant words by sampling them less often.
- Objective. Maximize the sum of over the emitted pairs, by stochastic gradient ascent. After training, the rows of are the word embedding; the output table is usually discarded.
The standing assumptions are a closed vocabulary, a bag of context words (the position inside the window does not enter ), 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:
SKIP-GRAM-LOSS(w_1..w_N, C, W_in, W_out)- 1
for t ← 1 to N do - 2
R ← a uniform draw from {1, ..., C} - 3
for each j with 1 ≤ |j| ≤ R and 1 ≤ t + j ≤ N do emit (w_t, w_{t+j}) - 4
for each emitted pair (w, c) do h ← v_w ▷ the row of W_in - 5
s_x ← u_x · h for every x in V ▷ |V| dot products - 6
loss ← loss - (s_c - log Σ_x exp(s_x)) ▷ -log P(c | w)
What it counts
The model assigns the probability above to each context word, and the training loss is the cross-entropy over the emitted pairs. The gradient for one pair is
Example. Take , , and the output vectors , , , . The scores are , and the softmax gives
The loss of the pair (cat, sat) is nats. Its gradient with respect to is , so a gradient step moves toward .
Cost of one evaluation. With the full softmax, one pair costs dot products of length , that is time, for the loss and for the gradient. Each position has on average pairs, so a pass over tokens costs . This is too slow for a large vocabulary, and the model is trained with one of two approximations:
- hierarchical softmax, which replaces the scores by about binary decisions, per pair;
- negative sampling, which replaces the softmax by logistic terms, per pair, and no longer defines a normalized .
Mikolov et al. give the training complexity per token as (their equation 5, with and ), which counts one input vector and a hierarchical softmax for each of about 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 , 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 , 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 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 be the number of emitted pairs and . If each row of scores could be set freely, the objective is maximized when for every word with .
Proof. The objective splits over . For a fixed , any distribution on satisfies with . By Gibbs' inequality, , with equality only at . Every distribution with full support is a softmax of some scores, and is approached as the scores of unseen pairs go to .
So the scores are determined only up to a constant per row, . With a finite , the matrix has rank at most , 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 is used is : 1 for and for . With the weights are . GloVe uses the weight for the same purpose.
Cost. The three training objectives cost (full softmax), (balanced hierarchical softmax; for a Huffman tree, the expected path length is within one bit of the entropy of the word distribution) and (negative sampling with noise words) per pair. The memory is 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.
# 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
- 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)
- 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
- Goldberg and Levy 2014, the skip-gram objective written as a sum over the word and context pairs of a corpus
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W0 stub |
|
Tag PV50G4 Edit this page History Report an error Markdown