Sub topic 9
The cost of the full softmax
This chapter assumes you know the dot product, the softmax function, and how a loss function drives gradient descent. It also assumes you have seen the skip-gram setup from the previous chapters: a center word predicts a nearby context word. Here you will see why the obvious way to turn that prediction into a probability is too expensive, and what that implies for the methods in the next chapters.
The model we want to train
Skip-gram gives every word two vectors. The center-word vector is v_c. The context-word vector (also called the output vector) is u_w. The probability of seeing context word o near center word c is a softmax over the whole vocabulary:
P(o | c) = exp(uo · vc) / Σw exp(uw · v_c)
The sum runs over all V words in the vocabulary. The training loss for one (center, context) pair is the negative log of this probability:
L = −uo · vc + log Σw exp(uw · v_c)
The first term is cheap. The second term, the log of the normalizer Z, is the problem. You cannot compute it without scoring every word in the vocabulary.
Where the cost comes from
For one training pair with embedding size d, the full softmax needs the following work:
- Scores. Compute
Vdot products of lengthd. This isV·dmultiply-adds. - Normalizer. Exponentiate and sum
Vnumbers. - Gradient for the center vector.
∂L/∂v_c = Σ_w (p_w − 1[w = o]) u_w. This is anotherV·doperations. - Gradient for the output vectors.
∂L/∂u_w = (p_w − 1[w = o]) v_cfor everyw. This is a thirdV·doperations, and it touches every row of the output matrix.
Step 4 matters most. Even a word that has nothing to do with this pair gets a small nonzero gradient, because its probability p_w is nonzero. So each update rewrites all V·d output parameters, not only a few rows.
A back-of-the-envelope estimate
Take a realistic setup: V = 1,000,000 words, d = 300, and a corpus of one billion tokens. With a window of 5 on each side, you get several billion training pairs. Say 5 × 10⁹ pairs.
- Per pair, the three steps cost about 3 ×
V·d= 9 × 10⁸ multiply-adds. - Over the corpus, that is about 4.5 × 10¹⁸ multiply-adds for one epoch.
- A CPU core sustains perhaps 10⁹ to 10¹⁰ useful multiply-adds per second on this kind of code.
That puts one epoch at years of single-core time. Multiple cores and GPUs help, but not by a factor large enough to hide the V term. The cost grows linearly with vocabulary size, and vocabularies of 10⁵ to 10⁶ words are normal.
Measuring it
The script below compares one full-softmax gradient step with a step that touches only the true context word and k = 5 randomly chosen words. The second step is the idea behind negative sampling, which is the next chapter. It is a different loss, not an approximation you can swap in unchanged. The point here is only the difference in work per step.
import time
import numpy as np
rng = np.random.default_rng(0)
V, d, k = 50_000, 100, 5
U = rng.normal(scale=0.1, size=(V, d)).astype(np.float32) # output vectors
v_c = rng.normal(scale=0.1, size=d).astype(np.float32) # center vector
o = 123 # true context word id
def full_softmax_step(U, v_c, o):
scores = U @ v_c # V dot products
scores -= scores.max() # stability: avoids overflow in exp
p = np.exp(scores)
p /= p.sum()
loss = -np.log(p[o])
p[o] -= 1.0 # p_w - 1[w == o]
grad_U = np.outer(p, v_c) # V x d: every row changes
grad_v = U.T @ p # sum over all V rows
return float(loss), grad_U, grad_v
def sampled_step(U, v_c, o, k, rng):
idx = np.concatenate(([o], rng.integers(0, U.shape[0], size=k)))
labels = np.zeros(k + 1, dtype=np.float32)
labels[0] = 1.0
rows = U[idx] # only k + 1 rows
p = 1.0 / (1.0 + np.exp(-(rows @ v_c)))
g = p - labels
grad_rows = np.outer(g, v_c) # (k + 1) x d
grad_v = rows.T @ g
return grad_rows, grad_v
def timeit(fn, repeats=200):
start = time.perf_counter()
for _ in range(repeats):
fn()
return (time.perf_counter() - start) / repeats
t_full = timeit(lambda: full_softmax_step(U, v_c, o))
t_samp = timeit(lambda: sampled_step(U, v_c, o, k, rng))
print(f"full softmax: {t_full * 1e3:.3f} ms per pair")
print(f"{k + 1} rows only: {t_samp * 1e3:.3f} ms per pair")
print(f"ratio: {t_full / t_samp:.0f}x")The exact numbers depend on your machine. The ratio is typically in the hundreds, and it grows if you raise V. Try V = 500_000 and watch the full-softmax time scale roughly tenfold while the sampled time barely moves.
Edge cases and gotchas
- Numerical stability.
exp(u_w · v_c)overflows quickly for large scores. Subtracting the maximum score before exponentiating, as the code does, leaves the probabilities unchanged and keepsexpin range. Deep learning libraries do this inside their log-softmax functions. - Memory. The output matrix has
V·dentries. AtV = 10⁶andd = 300in float32, that is 1.2 GB for the output vectors alone, and the dense gradientgrad_Uis the same size if you materialize it. - Hardware. A single softmax over
Ventries is a reduction across the whole vocabulary. It parallelizes poorly across asynchronous workers, because every worker wants to write to every row. - Frequent words dominate. Words like "the" get high probability in most contexts. Under the full softmax, the model spends much of its gradient on pushing their scores around, which is one motivation for subsampling frequent words later.
- Exact probabilities are not the goal. word2vec's purpose is useful vectors, not a calibrated language model. That is why cheaper objectives that only approximate the softmax's effect on the vectors work well in practice.
What the cost motivates
Two families of fixes appear in word2vec, and both follow from the analysis above.
| Approach | Idea | Work per pair |
|---|---|---|
| Full softmax | Normalize over all `V` words | `O(V·d)` |
| Negative sampling | Replace the normalizer with a few binary classification tasks against `k` sampled words | `O((k + 1)·d)` |
| Hierarchical softmax | Arrange words in a binary tree, so a word's probability is a product of decisions along its path | `O(log V · d)` |
Both attack the same term: the sum over V in the normalizer. The next chapter covers negative sampling in detail. Hierarchical softmax follows after it.
Exercise
A skip-gram model has V = 200,000 words and d = 200. Using the cost model above (three passes of V·d multiply-adds per pair), how many multiply-adds does one full-softmax training pair need? Then, if you switch to a scheme that touches the true context word plus 10 sampled words, roughly how many times less work is that per pair, ignoring the cost of sampling?
Show answer
Full softmax: 3 × 200,000 × 200 = 1.2 × 10⁸ multiply-adds per pair. The sampled scheme touches 11 rows, so its cost is about 3 × 11 × 200 = 6,600 multiply-adds. The ratio is 1.2 × 10⁸ / 6,600, or about 18,000 times less work. In practice the observed speedup is smaller, because fixed overheads such as memory access, random number generation and Python-level loops do not shrink with the number of rows.
Exercise
Why does a full-softmax update change the output vector of a word that is unrelated to the current training pair?
Show answer
The gradient for output vector uw is (pw − 1[w = o]) · vc. For a word that is not the true context word, the indicator is 0, so the gradient is pw · vc. The softmax assigns every word a nonzero probability pw, so the gradient is nonzero and the update pushes that word's score down a little. This is why the update touches all V rows.