DL0216 Word2Vec: CBOW, Skip-Gram and Negative Sampling

Before transformers there was word2vec. How do CBOW and skip-gram learn embeddings from raw text, and why does negative sampling make the training feasible?

A three-panel question card for an app-store search team. The first panel lists the training job: 1 billion review tokens, a 200,000-word vocabulary, 300-dimensional vectors, a window of 5 words each side, and about 6 billion training pairs per epoch, retrained every week on CPUs. The second panel shows one training pair, battery and drains, feeding a step that scores all 200,000 words, next to word counts of 48 million for the and 40 for haptics. The third panel asks which architecture, CBOW or skip-gram, and which output layer, full softmax, hierarchical softmax, or negative sampling with k equal to 5, to choose.

The Problem: A search team at an app store needs 300-dimensional word vectors from 1 billion review tokens over a 200,000-word vocabulary, retrained every week on CPUs. A full softmax would score all 200,000 words for each of about 6 billion training pairs per epoch, rare terms such as “haptics” occur only 40 times, and the team must choose CBOW or skip-gram plus an output layer.

Answer

Word2vec slides a window over raw text and trains a shallow two-matrix model to predict words from their neighbors, so words that share contexts end up with similar vectors. CBOW averages the context vectors and predicts the center word, which is fast but blurs rare words into the average. Skip-gram predicts each context word from the center word, which yields more training pairs per token and better vectors for rare words. The bottleneck is the output layer, because a full softmax must score all V vocabulary words for every pair. Negative sampling replaces that normalization with k+1 binary logistic tasks that separate the true pair from k noise words, cutting the per-pair cost from O(V) to O(k). Together with subsampling of frequent words, this makes training on billions of tokens feasible on ordinary CPUs.

(1) Self-Supervised Windows: Every corpus position with window radius c yields (center, context) examples for free, so no labels are needed and the distributional hypothesis does the teaching.
(2) CBOW Averages, Skip-Gram Fans Out: CBOW makes one prediction per window from the mean of 2c context vectors. Skip-gram makes up to 2c separate predictions, several times slower but giving every rare occurrence its own gradient.
(3) The Softmax Bottleneck: Normalizing over the vocabulary costs O(Vd) per pair and the gradient touches all V output vectors, about 6 \times 10^7 multiply-adds at V = 200{,}000 and d = 300.
(4) Hierarchical Softmax: A binary Huffman tree over the vocabulary turns one prediction into about \log_2 V sigmoid decisions, roughly 18 for 200,000 words and fewer for frequent words with short codes.
(5) Negative Sampling: Push the true pair’s score up and k noise pairs’ scores down with independent sigmoids, drawing noise from f(w)^{3/4}. Values of k from 5 to 20 suit small corpora and 2 to 5 suit large ones.
(6) Subsampling Frequent Words: Discarding tokens of “the” or “a” with probability 1-\sqrt{\tau/f(w)} speeds training 2 to 10 times and sharpens rare-word vectors by widening the effective window.
(7) Linear Geometry: The input vectors become the embeddings, and because the skip-gram negative-sampling optimum is a shifted PMI factorization, consistent relations appear as directions, as in v_{\mathrm{king}} - v_{\mathrm{man}} + v_{\mathrm{woman}} \approx v_{\mathrm{queen}}.

The two architectures read the same window in opposite directions. In “a hot foamy latte with cinnamon” with c = 2, CBOW forms one example: average the input vectors of hot, foamy, with, and cinnamon, then predict latte. Skip-gram forms four examples, (latte, hot), (latte, foamy), (latte, with), and (latte, cinnamon), and v_{\mathrm{latte}} receives a separate gradient from each. CBOW’s averaging is a smoothing step, so frequent words get stable vectors quickly and an epoch is several times cheaper. A rare word, though, only ever appears as one of 2c averaged inputs or as a target predicted from common context. Skip-gram spends more compute per token, yet every occurrence of a rare word is a full training signal for its own vector, which is why the original word2vec tool from Google recommends it for infrequent words and windows around 10.

Two side-by-side panels for the window a hot foamy latte with cinnamon. Left, CBOW: four context word boxes, hot, foamy, with, and cinnamon, each send an arrow into one box that averages the four context vectors, which sends one arrow to a box that predicts the center word latte, with a note that there is one prediction per window and a rare word is diluted in the average. Right, skip-gram: one center box latte sends four arrows to the four context word boxes, with a note that the window gives four center-context pairs and each arrow becomes one negative-sampling task.

Figure 1: The same window with c = 2 read two ways. CBOW averages four context vectors into h_t and makes one prediction of the center word, while skip-gram turns the window into four (center, context) pairs, each trained as its own negative-sampling task.

PropertyCBOWSkip-gram
Prediction directionAveraged context predicts the center wordCenter word predicts each context word separately
Examples per token1Up to 2c, about c + 1 on average with dynamic windows
Training speedSeveral times faster per epochSlower, roughly proportional to the window size
Rare wordsDiluted in the context average and rarely a targetEvery occurrence updates its own vector directly
Analogy accuracy (Mikolov et al., 640-d)About 64% syntactic, 24% semanticAbout 59% syntactic, 55% semantic
Recommended windowAround 5Around 10
Good default forVery large corpora, frequent-word quality, fast iterationSmaller corpora, rare words, semantic similarity

The output layer decides feasibility. The model keeps two matrices, W_{\mathrm{in}} and W_{\mathrm{out}}, each of shape V \times d, and the input side is a single row lookup. A full softmax needs V dot products for its normalizer and produces a dense gradient over all of W_{\mathrm{out}}, which at the sizes above is 6 \times 10^7 multiply-adds for one pair. Hierarchical softmax keeps a properly normalized distribution by factorizing it along a Huffman tree at about d \log_2 V cost. Negative sampling drops normalization altogether. It never estimates p(o \mid c); instead it trains a classifier that separates observed pairs from noise pairs, which is all an embedding needs. Each update touches one input row and k+1 output rows, so lock-free parallel SGD across CPU threads rarely collides.

Mathematical Formulation:
J = \frac{1}{T}\sum_{t=1}^{T}\sum_{1 \leq |j| \leq c}\log p(w_{t+j} \mid w_t)
p(o \mid c) = \frac{\exp(u_o^{\top} v_c)}{\sum_{w=1}^{V}\exp(u_w^{\top} v_c)}
h_t = \frac{1}{2c}\sum_{1 \leq |j| \leq c} v_{w_{t+j}}
\ell_{\mathrm{NS}} = -\log \sigma(u_o^{\top} v_c)
\quad - \sum_{i=1}^{k}\log \sigma(-u_{n_i}^{\top} v_c)
n_i \sim P_n(w) \propto f(w)^{3/4}
P_{\mathrm{drop}}(w) = 1 - \sqrt{\tau / f(w)}

Where:

  • J is the skip-gram objective, an average over T corpus positions t; c is the maximum window radius (resampled uniformly from 1 to c at each position in the reference implementation) and j is the offset to a context word w_{t+j}.
  • p(o \mid c) is the full softmax probability of context word o given center word c, and its denominator sums over all V vocabulary words, which is the O(V) bottleneck.
  • v_c \in \mathbb{R}^{d} is the input vector of the center word (a row of W_{\mathrm{in}}) and u_o the output vector of a context word (a row of W_{\mathrm{out}}), with d typically 100 to 300.
  • h_t is CBOW’s averaged context vector, which takes the place of v_c in both the softmax and the negative-sampling loss, with the center word w_t as the target.
  • \ell_{\mathrm{NS}} is the per-pair negative-sampling loss, \sigma(x) = 1/(1+e^{-x}) is the logistic function, and k is the number of noise words n_i drawn for each true pair.
  • P_n is the noise distribution, the unigram frequency f(w) raised to the power 3/4 and renormalized, which flattens the head of the distribution toward rarer words.
  • P_{\mathrm{drop}}(w) is the probability of discarding a token before windowing, with threshold \tau \approx 10^{-5}; words with f(w) \leq \tau are never dropped.

Negative sampling is easiest to understand through its gradient. Writing \sigma_o = \sigma(u_o^{\top} v_c) for the true pair and \sigma_i = \sigma(u_{n_i}^{\top} v_c) for each noise pair, differentiating \ell_{\mathrm{NS}} gives three sparse updates.

Negative-Sampling Gradients:
\nabla_{v_c}\ell = (\sigma_o - 1)\,u_o + \sum_{i=1}^{k}\sigma_i\,u_{n_i}
\nabla_{u_o}\ell = (\sigma_o - 1)\,v_c
\nabla_{u_{n_i}}\ell = \sigma_i\,v_c

Take d = 2 and one skip-gram pair (latte, espresso) with a single noise word, tractor, so k = 1. Let v_c = (0.5, 0.5) for latte, u_o = (1, 0) for espresso, u_n = (0, 1) for tractor, and use a learning rate of 0.2.

Worked Example:
\sigma_o = \sigma(u_o^{\top} v_c) = \sigma(0.5) = 0.62
\sigma_n = \sigma(u_n^{\top} v_c) = \sigma(0.5) = 0.62
\nabla_{v_c}\ell = -0.38\,u_o + 0.62\,u_n = (-0.38,\ 0.62)
v_c' = v_c - 0.2\,\nabla_{v_c}\ell = (0.58,\ 0.38)
u_o^{\top} v_c' = 0.58
u_n^{\top} v_c' = 0.38

One step moved latte toward espresso and away from tractor, and the pair loss fell from 1.45 to about 1.34. The two scalars are the error signals. 1-\sigma_o = 0.38 measures how far the true pair is from being classified as real, and \sigma_n = 0.62 measures how strongly the noise pair is mistaken for real. Both shrink as training succeeds, so easy pairs stop producing updates. The output vectors move in the same step, computed from the old v_c: espresso gains 0.2 \times 0.38 \times v_c = (0.038, 0.038) and tractor loses (0.062, 0.062).

Two panels. Left: a log-scale bar chart of output-layer multiply-adds for one training pair at a vocabulary of 200,000 words and 300 dimensions, with bars of 60,000,000 for full softmax, 5,400 for hierarchical softmax, 4,800 for negative sampling with k equal to 15, and 1,800 for negative sampling with k equal to 5, and a note that k equal to 5 does about 33,000 times less output work than the full softmax. Right: a two-dimensional plot of the worked example with the espresso output vector along the first axis, the tractor noise vector along the second axis, the latte center vector at 0.5, 0.5 before the step, and at 0.58, 0.38 after one step, with a box listing the true score rising from 0.50 to 0.58, the noise score falling from 0.50 to 0.38, and the pair loss falling from 1.45 to 1.34.

Figure 2: (a) Output-layer work for one pair at V = 200{,}000 and d = 300 on a log scale: the full softmax needs 60 million multiply-adds, hierarchical softmax about 5,400, and negative sampling 1,800 at k = 5. (b) The worked example: one step moves v_c toward espresso and away from tractor, raising the true score from 0.50 to 0.58 and lowering the noise score to 0.38.

The remaining knobs have predictable effects. A small window of 2 favors syntactic and functional similarity, so the neighbors of “walking” are other gerunds, while a window of 10 favors topical relatedness, so “espresso” lands near “barista”. Dimensions beyond about 300 rarely improve analogy accuracy without more data, and a min_count of 5 discards words too rare to estimate at all. The famous analogy is a cosine nearest-neighbor search for v_b - v_a + v_{a'} with the three query words excluded. Without that exclusion the answer to the king, man, woman query is usually king itself, a detail that makes the linear structure look cleaner than it is.

Word2vec also opens a lineage: word2vec → GloVe → fastText → ELMo → BERT. GloVe fits the same global co-occurrence statistics directly with weighted least squares, and fastText builds each vector from character n-grams so misspelled or unseen words still get one. The decisive limit is that word2vec stores one static vector per word type, so “bank” gets the same vector beside “river” and beside “loan”. ELMo and BERT fixed that with contextual embeddings computed per occurrence, and BERT’s masked-language-model objective is essentially CBOW made deep, predicting a hidden token from its full bidirectional context. Modern LLMs such as Llama 3 still start from a word2vec-style lookup table but pay the full softmax over a 128,256-token vocabulary, because GPU matrix multiplies make O(V) affordable and generation needs a normalized distribution.


Login to view more content
Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *